text stringlengths 37 1.41M |
|---|
v = int(input('Informe um número inteiro: '))
print('O doblo de {} é {}'.format(v, v*2))
print('O triplo de {} e {}'.format(v, v*3))
print('A raiz quadrade de {} e {:.2f}'.format(v, v**(1/2)))
|
lista = [[], [], [], []]
for l in range(0, 4):
for c in range(0, 4):
lista[l].append(int(input(f'Digite um valor para [{l}, {c}]: ')))
for l in lista:
for c in l:
print(f'[ {c:>3} ]', end='')
print()
|
nota1 = float(input('Informe a 1ª nota: '))
nota2 = float(input('Informe a 2ª nota: '))
media = (nota1 + nota2) / 2
print('Média: {:.1f} - '.format(media), end='')
if media < 5.0:
print('Aluno REPROVADO!')
elif 5.0 <= media <= 6.9:
print('Aluno em RECUPERAÇÃO')
else:
print('Aluno APROVADO')
|
mt = float(input('Informe a medida (em metros): '))
print('{} metros = {:.0f} centímetros'.format(mt, mt * 100))
print('{} metros = {:.0f} milímetros'.format(mt, mt * 1000))
|
num1 = int(input('Digite 1º número: '))
num2 = int(input('Digite 2º número: '))
if num1 > num2:
print('O 1º número é maior.')
elif num1 < num2:
print('O 2º número e maior')
else:
print('Não existe valor maior, os dois são iguais.')
|
print('{:=^40}'.format(' LOJA DO ZÉ '))
preco = float(input('Preço normal: (R$) '))
print('Condições de pagamento:')
print('1-Á vista (dinheiro/cheque) desconto -10%')
print('2-Á vista (cartão) desconto -5%')
print('3-Em até 2x (cartão) preço normal ')
print('4-3x ou mais (cartão) acréscimo +20%')
op = int(input('Escol... |
import numpy as np
def gini(array):
"""Calculate the Gini coefficient of a numpy array.
https://github.com/oliviaguest/gini/blob/master/gini.py
based on bottom eq:
http://www.statsdirect.com/help/generatedimages/equations/equation154.svg
from:
http://www.statsdirect.com/help/default.htm#nonpara... |
# 호텔 방 배정 (https://programmers.co.kr/learn/courses/30/lessons/64063)
# 시간 효율성 풀이 => (https://m.blog.naver.com/js568/221957852279)
# 더 깔끔한 풀이 (https://programmers.co.kr/learn/courses/30/lessons/64063/solution_groups?language=python3)
# 재귀는 모두 iterative 하게 바꿀 수 있음을 유의!!
import sys
sys.setrecursionlimit(10000) # 재귀 허용깊이 임... |
# 입력
N = int(input())
market = list(map(int,input().split()))
M = int(input())
needs = list(map(int, input().split()))
market.sort()
# 이진 트리 탐색 구현
def binary_search(arr, target, start, end):
if start > end:
return False
mid = (start + end) // 2
if arr[mid] == target:
return True
... |
def binary_search(arr, target, start, end):
if start > end:
return None
mid = (end + start) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target :
return binary_search(arr, target, start, mid - 1)
else:
return binary_search(arr, target, mid + 1, end)
... |
import datetime
def checking_Id(check):
if users_ID.get(check, "none") == "none":
return False
else:
return True
class User:
def __init__(self, Id="0", credit=0):
self.__Id = Id
self.__password = ""
self.__credit = credit
self.__statement ... |
def solve(left, right, accuracy, func, derivative):
x0 = 0
if derivative(left) > derivative(right):
x0 = left
else:
x0 = right
lambd = -1 / derivative(x0)
x = lambd * func(x0)
iterations = 0
print('iterations x0 xi func(xi) xi-x0')
while abs(func(x)) > accuracy and abs... |
import math
class Circle():
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
a_circle = Circle(4)
print(a_circle.area())
|
list1 = [8, 19, 148, 4]
list2 = [9, 1, 33, 83]
result = []
for i in list1:
for j in list2:
result.append(i * j)
print(result)
|
import random
pick_amount = int(input("How many quick picks? >> "))
i = 0
for pick_amount in range(1, pick_amount+1, 1):
numbers = []
for i in range(1, 6, 1):
number_generate = random.randint(1, 45)
if number_generate in numbers:
numbers.remove(number_generate)
number_g... |
def score_calc(in_score):
if in_score < 0:
result = "Invalid Score"
elif in_score > 100:
result = "Invalid Score"
elif in_score > 90:
result = "Excellent"
elif in_score > 50:
result = "Acceptable"
else:
result = "Bad"
return result
score = float(input("... |
def summation(current_number, accumulated_sum):
# base case
# return the final state
if current_number == 11:
return accumulated_sum
# recursive case
# thread the state through the recursive call
else:
return summation(current_number + 1, accumulated_sum + current_number)
if _... |
def sum1(n):
# base case
if n == 0:
return 2 ** 0
# recursive case
return 2 ** n + sum1(n - 1)
def sum2(n):
# base case
if n == 1:
return 2
# recursive case
return (n * (n + 1)) + (sum2(n - 1))
user_n = int(input("Please enter the value of n: "))
print("The value o... |
import itertools
def bin_count(size):
for i in itertools.product([0, 1], repeat=size):
yield i
size_of = int(input("Please enter the size of S: "))
set_A = [int(char) for char in input("Please enter the elements of S: ")]
N = int(input("Please enter the number N: "))
all_subsets = []
for binary in bin_c... |
#! usr/bin/env python #
# -*- coding: utf-8 -*-
"""
Posical is a Python 3 module that models a generalized calendar reform with regularly-sized weeks and months and an intercalary period, based on August Comte's Positivist Calendar.
"""
import datetime,operator
from calendar import isleap as std_isleap
from nonzero i... |
import regex as re
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
def find_hashtags(tweet):
"""This function will extract hashtags"""
return re.findall('(#[A-Za-z]+[A-Za-z0-9-_]+)', tweet)
def hashtag_correlations(Data, republican=False, democrat=False):
for i in range(len(Dat... |
# coding:utf-8
"""
@Author : Cong
@Time : 2021/6/17 14:13
"""
class Kid:
def __init__(self, gid):
self.gid = gid
self.left = None
self.right = None
class Cycle:
def __init__(self, count):
self.head = None
self.tail = None
for i in range(count):
... |
##MTH TO LAST ELEMENT
##SPONSORING COMPANY:
##
##CHALLENGE DESCRIPTION:
##
##Write a program which determines the Mth to the last element in a list.
##
##INPUT SAMPLE:
##
##The first argument is a path to a file. The file contains the series of
##space delimited characters followed by an integer. The integer represents... |
##DISTINCT SUBSEQUENCES
##CHALLENGE DESCRIPTION:
##
##A subsequence of a given sequence S consists of S with zero or
##more elements deleted. Formally, a sequence Z = z1z2..zk is a
##subsequence of X = x1x2...xm, if there exists a strictly increasing
##sequence of indicies of X such that for all j=1,2,...k we have
##Xi... |
"""
Class notes for Lucille Brown Mondays - Intro to Computer Science
"""
# 10/2
# General Introductions: name, age, coding experience, techem
# What is computer science, computers, programming/coding
# terminal:
# mkdir student_name
# geany helloworld.py
print "Hello World!"
pr... |
#!/usr/bin/env python3
import socket
import os
import threading
import socketserver
SERVER_HOST = 'localhost'
SERVER_PORT = 0
BUF_SIZE = 1024
ECHO_MSG = 'Hello echo server!'
class ThreadedClient():
""" A client to test a multithreaded server """
def __init__(self, ip, port):
# Create a socket
self.... |
def get_anagram_diff_report(a, b):
a_hashmap = get_frequency_hashmap(a)
b_hashmap = get_frequency_hashmap(b)
chars_to_remove_from_a = get_char_difference(a_hashmap, b_hashmap)
chars_to_remove_from_b = get_char_difference(b_hashmap, a_hashmap)
return "remove {cnt_a} characters from '{a}' and {cnt_b... |
#!/bin/python3
import sys
"""
Bubble sort method
"""
n = int("3".strip())
a = list(map(int, "3 2 1".strip().split(' ')))
#a = list(map(int, "1 2 3".strip().split(' ')))
iSwaps = 0
for _ in range(n):
for j in range(n-1):
if a[j]>a[j+1]:
iTemp=a[j+1]
a[j+1]=a[j]
a[j]=iTem... |
"""Reaction file."""
import json
import random
class Reactions:
"""Check if there is expected word in "reactions" dict to generate phrases
from GrandPyBot.
In : reactions (dict)
Act : compare words in "reactions" list, with expected words, like 'HELLO'
create a string with messages concata... |
#FALTA HACER METODO DE IMPRESION DE LA TABLA DE HASH
class entry:
def __init__(self, nombreID,blockID,tipo,mundoId,tareaId):
self.nombreID = nombreID
self.blockID = blockID
self.tipo = tipo
self.mundoId = mundoId
self.tareaId = tareaId
class leblancCook:
def __init... |
from reinforcement_learning.Tic_tac_toe.GameBoardState import GameBoardState
import numpy as np
import re
class Human_player_interface:
def __init__(self, player_mark : int):
self.player_mark: int = player_mark
assert player_mark in [1, 2]
def choose_next_action_play(self, in_gamebo... |
def binary_search(arr,x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high :
mid = (low + high) // 2
if arr[mid] < x :
# ignoring left half
low = mid + 1
elif arr[mid] > x :
# ignoring right half
high = mid - 1
else :... |
import json
import random
#CAMINHOS MINIMOS
#carrega o grafo atraves do arquivo Json
g = json.load(open('data5.json'))
#retorna os vizinhos do vertice solicitado no grafo
def vizinhos(grafo,v):
v = str(v)
vizinhos = []
arestas = grafo["arestas"]
for par in arestas: #par percorre as arestas
if... |
import random # generate account number for new user
import time # show time to user upon login
import validation
import database
from getpass import getpass
localtime = time.asctime(time.localtime(time.time()))
print("Current local time is :", localtime)
# register
# - first name, last name , email
# - generate u... |
# liste = [1, 2, 3, 4, 5, 6, 7, 8]
# liste[:round(len(liste)/2)], liste[round(len(liste)/2):] = liste[round(len(liste)/2):], liste[:round(len(liste)/2)]
# print(liste)
###########
n = int(input("Please, enter a single digit integer"))
if 0 <= n < 10:
for i in range(n):
if i%2==0:
print(i)
|
def find_Words(text, mot):#prend une liste de string et un mot
taille = len(text) #on calcule la taille du texte
mot= ' ' + mot + ' '#on rajoute des espaces avant et apres le mot
taille3=len(mot) #on calcule la taille du mot
dico=dict() #on initialise un dico pour faire toutes les parties
... |
% python
>>> string1 = 'Wakanda'
>>> string2 = 'Forever'
>>> string1 + string2
'WakandaForever'
>>> string1 + " Pride " + string2
' Wakanda Pride Forever '
>>> string3 = string1 + string2 + "Strength"
>>> string3
'WakandaForeverStrength'
>>> string3[2:10] #string 3 from index 2 (0-based) to 10
|
# http://codeforces.com/problemset/problem/112/A
s1 = input()
s2 = input()
s1 = s1.lower()
s2 = s2.lower()
if s1<s2:
print("-1")
elif s2<s1:
print("1")
else:
print("0") |
# http://codeforces.com/problemset/problem/131/A
s = input()
if s[0].islower() and s[1:].isupper():
print(s.capitalize())
elif s.isupper():
print(s.lower())
elif len(s)==1 and s.islower():
print(s.upper())
else:
print(s) |
# http://codeforces.com/problemset/problem/405/A
input()
li = list(map(int, input().split()))
li.sort()
for l in li:
print(l, end=' ') |
# http://codeforces.com/problemset/problem/486/A
n = int(input())
_sum = int(n/2)
if n%2 == 0:
print(_sum)
else:
print("-"+str(_sum+1))
|
#Method 2 - Bubble Sort
def bubble_sort(list2):
# Traverse (travel across) through every element on the list
for i in range(0, len(list2) - 1):
# Compare each item in list 1 by 1. Comparison in each iteration
# will shorten as the last elements become sorted
for j in range(0, len(list2... |
import numpy as np
# input list
a = [[1,2,3],[4,5,6]]
# convert to numpy array
b = np.array(a, float)
# number of dimensions => 2
print(b.ndim)
# number of rows and columns => (2,3)
print(b.shape)
#data type => float64
print(b.dtype)
# Slicing operations
# : in first argument means do this on all dimensions => ... |
'''
Created on Jul 24, 2018
@author: Anil.Kale
'''
# printing 0 to 5, default increment is 1
for x in range(6):
print(x)
print()
# printing 2 to 5
for x in range(2,6):
print(x)
print()
# printing from 2 to 15 with 3 as increment
for x in range(2, 15, 3):
print(x) |
'''
Created on Jul 26, 2018
@author: Anil.Kale
'''
class MyClass:
x = 5
print (x)
#create an object of class and access the variable
obj = MyClass()
print (obj.x) |
import math, copy
class Board(object):
def __init__(self, board):
self._board = board
self._size = int(math.sqrt(len(board)))
"""
Returns:
-100 - winner is X player
100 - winner is O player
0 - it is tie
None - game is still active
... |
#!/usr/bin/python3
#Made by Kirill Shvedov
my_name = "kirill"
x = "second_half"
alphabet = [1,2,3,4,5,6,7,8,9,10,
11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26] #numbers of letters in the alphabet
name_leters = list(my_name)
#name_leters.append("k")
#name_leters.append("i")
#name_leters.append("r")
#name_leters.... |
'''
'''
class Node:
def __init__(self,val):
self.val = val
self.next = None
if __name__=="__main__":
elements = [1,2,3,4,5]
head = Node(0)
temp = head
for element in elements:
temp.next = Node(element)
temp = temp.next
head = head.next
temp = head
... |
def longestPeak(array):
longestPeakLength = 0
i = 1
while i < len(array)-1:
peak = array[i-1] < array[i] and array[i] > array[i+1]
if not peak:
i += 1
continue
lIdx = i - 2
while lIdx >= 0 and array[lIdx] < array[lIdx+1]:
lIdx -= 1
... |
def arrayOfProducts(array):
products = [1 for _ in range(len(array))]
for i in range(len(array)):
temp = 1
for j in range(len(array)):
if j != i:
temp *= array[j]
products[i] = temp
return products
print(arrayOfProducts([5, 1, 4, 2]... |
import random as R
count = 0
x = R.randint(0,100)
while True:
y = int(input("请输入一个整数:"))
count += 1
if y == x:
print("恭喜您猜对了!!!")
break
elif y < x:
print("您输入的数字太小,再接再厉~")
elif y > x:
print("您输入的数字太大,再接再历~")
print("您猜了", count, '次数字')
|
# 一、定义列表:list1 = ['life','is','short'],
# list2 = ['you','need','python']
# 完成以下几个要求:
# 1)输出python及其下标
# 2)将 'python' 改为 'python3'
# 3) 将list1和list2合并构造集合 list_set2
# list1 = ['life','is','short']
# list2 = ['you','need','python']
# print(list2[2], list2.index('python'))
# list2[2] = 'pytho... |
# file_open.py
# 此示例示意读取当前文件夹下myfile.txt这个记录文字信息的
# 文件
# 1.打开文件
try:
myfile = open('myfile.txt') # 成功打开文件
# myfile = open('我不存在.txt') # 失败
print("文件打开成功")
# 2. 读/写文件
# 3. 关闭文件
myfile.close()
print("文件关闭成功")
except OSError as O: # OSError表示无法进行输入输出
print('文件打开失败!', O)
|
#此示例示意函数可以返回另一个函数的引用关系
def get_function():
s = input("请输入你要做的操作")
if s == "求最大":
return max
elif s == "求最大":
return min
elif s == "求最大":
return max
else:
return print
L = [2, 4, 6, 8, 10]
f = get_function() #相当于f绑定 max(),min(),max()
print(f(L))
|
# 写程序将这些数据读取出来,并以如下格式打印在屏幕终端上
# 小张 今年 20 岁,成绩是: 100
# 小李 今年 18 岁,成绩是: 98
# 小赵 今年 19 岁,成绩是: 80
# def read_info_from_file():
# '''此函数将从文件中读取信息
# 形成字典的列表'''
# L = []
# try:
# fr = open('info.txt', 'rt')
# # 读取数据放在列表L中
# for line in fr: # line = '小张 20 100\n'
# ... |
#try_except.py
def div_apple(n):
print("%d个苹果你想分给几个人?" % n)
s = input('请输入人数:')
count = int(s) #<---可能触发ValueError错误
result = n / count #<---可能触发ZeroDivisionError错误
print("每人分了", result, '个苹果')
try:
div_apple(10)
print("分苹果成功")
# except ValueError as VE:
# print("分苹果失败,苹果被收回", VE)
# ... |
# 1. 写一个程序,输入您的出生日期(年月日)
# 1) 算出你已经出生多少天?
# 2) 算出你出生那天是星期几?
import time
y = int(input("请输入出生的年: "))
m = int(input("请输入出生的月: "))
d = int(input("请输入出生的日: "))
# 第一步算出出生时的计算机元年的秒数
birth_tuple = (y, m, d, 0, 0, 0, 0, 0, 0)
birth_second = time.mktime(birth_tuple)
# 得到当前时间的秒数
cur_second = time.time()
# 算出出生的秒数
... |
# Blueprint:
class Car:
wheels = 4 #Class Variable - all objects have this by default
def __init__(self, size, brand, year, color):
self.size = size # Instance Variable: can change for each object
self.brand = brand # Instance Variable
self.year = yea... |
# is_pair함수는 문자열 s를 매개변수로 입력받습니다.
# s에 괄호가 알맞게 짝지어져 있으면 True를 아니면 False를 리턴하는 함수를 완성하세요.
# 예를들어 s가 (hello)()면 True이고, )(이면 False입니다.
# s가 빈 문자열("")인 경우는 없습니다.
def is_pair(s):
ch_stack = []
for ch in s:
if ch == '(':
ch_stack.append(ch)
elif ch == ')':
try:
... |
# 앞뒤를 뒤집어도 똑같은 문자열을 palindrome이라고 합니다.
# longest_palindrom함수는 문자열 s를 매개변수로 입력받습니다.
# s의 부분문자열중 가장 긴 palindrom의 길이를 리턴하는 함수를 완성하세요.
# 예를들어 s가 토마토맛토마토이면 7을 리턴하고 토마토맛있어이면 3을 리턴합니다.
def is_palindrom(s):
return s == s[::-1]
assert (is_palindrom('토마토'))
assert (not is_palindrom('토마토마'))
def longest_palindrom(s):
... |
#coding: utf-8
#文字列の連結
a = 'python'
b = '2.7'
c = a + b
print c
#文字列配列の結合
strings = ['dog','cat','penguin']
print ','.join(strings)
#文字列の繰り返し
s = 'dog?'
print s * 3
#値の埋め込み
#sprintf
a = "python"
b = "a programming language"
print "%s is %s" % (a,b)
#拡張sprintf
v = dict(first = "Michael", family = "Jackson")
print "H... |
#coding: utf-8
class MyClass:
"""A sample class"""
PI = 3.14
def __init__(self):
self.name = ""
def getName(self):
return self.name
def setName(self,name):
self.name = name
a = MyClass()
a.setName("Tanaka")
print a.getName()
print MyClass.PI
class MyClass:
def __init__(self):
self.name = ""
a1 = My... |
import math
def i2arr(n): # write Fibonacci series up to n
"Print array"
result=[]
while n>9:
b=n%10
result.append(b)
n=int(n/10)
result.append(n)
return result
def check_palindrom(array): # write Fibonacci series up to n
flag=1
n=len(array)
#for... |
def fib(n): # write Fibonacci series up to n
"Print a Fibonacci series up to n"
result=[]
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
f1000=fib(2000)
print f1000
|
print(type(42))
#python提供了内建函数。
#函数int接受任何值,并在其能做到的情况下,将该值转换成一个整型数,否则会报错。
print(int('32'))
#print(int('Hello'))
#int能将浮点数转换为整型数,但是他并不进行舍入;这是截掉了小数点部分。
print(int(3.99999))
print(int(-2.3))
#float可以将整型数和字符串转换为浮点数。
print(float(32))
print(float('3.14159'))
#string可以将实参转换成字符串。
print(str(32))
print(str(3.14159))
import math
p... |
def any_lowercase1(s):
for c in s:
if c.islower():
return True
else:
return False
def rotate_word(word,a):
if word.islower():
for letter in word:
b = ord(letter)
b = b + a
print(chr(b), end='')
elif not word.islower():
... |
def make_dict():
fin = open('words.txt')
s = dict()
for letter in fin:
word = letter.strip()
s[word] = None
return s
print(make_dict())
print('aahe' in make_dict()) |
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
def most_frequent(string):
t = list(string)
d = histogram(t)
max = 1
for key in d :
if d[key]>max:
max = d[key]
i = max
while i >=1:
... |
def nested_sum(t):
total = 0
for x in t:
total +=sum(x)
return total
t = [[1, 2], [3], [4, 5, 6]]
print(nested_sum(t)) |
import math
class Point:
"""Represents a point in 2-D space."""
print(Point)
blank = Point()
print(blank)
blank.x = 3.0
blank.y = 4.0
print(blank.y)
x = blank.x
print(x)
print('(%g, %g)' % (blank.x, blank.y))
distance = math.sqrt(blank.x**2 + blank.y**2)
print(distance)
def print_point(p):
print('(%g, %g)' % (... |
def cumsum(t):
s = []
for i in range(len(t)):
s.append(sum(t[:i+1]))
return s
t = [1, 2, 4,5]
print(cumsum(t))
|
fin = open('words.txt')
def has_no_e1(word):
for letter in word:
if letter == 'e':
return False
return True
print(has_no_e1('wired'))
def has_no_e2():
a = 0
b = 0
for line in fin:
a = a+1
if has_no_e1(line):
print(line)
b = b+1
print(b... |
"""Module convert angle"""
from typing import Union
import numpy as np
__all__ = ['degrees_to_rad', 'minutes_to_rad', 'seconds_to_rad', 'angle_to_rad']
def degrees_to_rad(degrees: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
"""
Convert angles in degrees to radians
:param degrees: angle in degr... |
import threading
# 继承方式创建线程的类, 再改写,添加方法
class ra(threading.Thread):
def __init__(self,name,data):
threading.Thread.__init__(self)
self.name = name
self.data = data
# run方法是唯一要调用的方法,也是最重要的方法
def run(self):
print(self.name+'sing'+self.data)
# 更多的方法必须由run()函数二次调用... |
import tkinter
# 建立一个窗口对象(容器)
win = tkinter.Tk() # 实例
win.title('我是一个窗口') # 窗口名称
win.geometry('400x400+600+20') # 窗口大小
# label标签控件
# text文本, bg 背景色, fg 字体颜色
label = tkinter.Label(win, text='我是一个控件', bg='red', fg='black',
width=10, height=4, justify='left')
label.place(x=200, y=100) # ... |
# generator solution
def even_integers_generator(n):
for i in range(n):
if i % 2 == 0:
yield i
def main():
even_nums = even_integers_generator(20)
print(list(even_nums))
if __name__ == "__main__": main() |
x = "James"
print('Hello World from {}'.format(x))
# f stands for format
print(f'Hello World from {x}')
|
#Joseph Day
#Project Euler
#112 Bouncy Numbers
def increasing(x):
digits = [int(d) for d in str(x)]
first = digits[0]
for digit in digits:
second = digit
if first > second:
return False
first = digit
return True
def decreasing(x):
return increasing(int(str(x... |
import sqlite3
class DB:
def __init__(self,dbname="bots.sqlite"):
self.dbname = dbname
self.conn = sqlite3.connect(dbname)
def setup(self):
cmd = "CREATE TABLE IF NOT EXISTS items (description text)"
self.conn.execute(cmd)
self.conn.commit()
def add_item(self,item_name):
cmd = "INSERT INTO items (des... |
#PDF excerpt tool
#initialize the environment
import os
import sys
import string
import importlib
#GUI interface class
import tkinter
import tkinter.messagebox
from tkinter import *
#import word document
#pip3 install python-docx to install (python-docx is compatible to Python3.x)
from docx import Document
def main(... |
from turtle import *
import turtle
t=turtle.Turtle()
def jump(distanz, winkel=0):
global number
t.penup()
t.right(winkel)
t.forward(distanz)
t.left(winkel)
t.pendown()
t.pensize(7)
rad=100
abc=19
bcd=19
number=1
for j in range(10):
for i in range(abc):
jump(rad)
... |
from math import *
from matplotlib import pyplot
from numpy import arange
'''
A sphere area in dimension D can be found by formula [\ V_{r} = K_{D}*r^{D} \]
We will find the ratio between the region r = 1 and r = 1 - \epsilon
[\ Ratio = (V_{1} - V{1-\epsilon} ) / V_{1} \] -----> Asses for values of D and... |
#2
def cube(num):
return num * num * num
def avg(a,b,c,d):
return (a + b + c + d) / 4
def triplicate(text):
return text + text + text
def multiplicate(text,number):
return text * number
#3
def extract_root(a,b,c):
a = int(str(a))
b = int(str(b))
c = int(str(c))
y1 = (- b + (b *... |
#1.
class Block:
"""have attributes to store the coordinates of the center of the Block
and for the width and height of the Block.
Attributes: center(tup of num),width(num),height(num)"""
#2.
def __init__(self,center,width,height):
"""take a pair* of coordinates (for the center),
... |
print('My name is Wu Shenyuan')
print("I like to playing computer games")
print("""Such as Dota2, starcraft and warcraft""")
print("The \nmost I"+" "+'like for this three is'+" "+"""Dota2""")
print('"It is "'),print("'interesting'")
|
#2.
def factorial(x):
"""takes a natural number and returns the product of all the natural numbers from 1 up to the given number.
natural num -> num"""
if x == 0:
return 0
elif x == 1 :
return 1
else:
return x * factorial(x-1)
#3.
def power_of_two(x):
"""t... |
#1.
class Thing:
"""representing physical objects in the game
Attribute: name(str),location(str)"""
def __init__(self,name,location):
"""take the name of object and the location of object
Thing,str,str -> None"""
self.name = name
self.location = location
... |
def make_counter():
"""Return a counter function.
>>> c = make_counter()
>>> c('a')
1
>>> c('a')
2
>>> c('b')
1
>>> c('a')
3
>>> c2 = make_counter()
>>> c2('b')
1
>>> c2('b')
2
>>> c('b') + c2('b')
5
"""
"*** YOUR CODE HERE ***"
record={}
... |
from criandoListaTxtDesejos.interface.produto import *
from criandoListaTxtDesejos.interface.efeito import *
arq = 'Lista_de_desejo.txt'
if not existeArqu(arq):
criarArquivo(arq)
while True:
linha2()
choice = lista(['Ler Lista de Desejos',"Adicionar item a Lista de desejos",'Fechar programa'])
... |
import time
import threading
import random
from pynput.mouse import Button, Controller
from pynput.keyboard import Listener, KeyCode
print("Welcome. This auto-clicker uses variance to click randomly within a certain specified time period.")
print("The variance is used in such a way that the time between clicks is set... |
def movies():
age=input("Enter age (child, middle school, high school, or other): ")
weather=input("Enter weather(rainy, sunny, hailing, snowing, or other): ")
if age=="child":
if weather=="sunny":
print("Pay $2.")
elif weather=="snowing":
print("Pay $1.50.")
... |
from collections import Counter
import nltk
UPPERCASE_LETTERS = [chr(i) for i in range(65, 91)]
LOWERCASE_LETTERS = [chr(i) for i in range(97, 123)]
LETTERS = UPPERCASE_LETTERS + LOWERCASE_LETTERS
STOP_WORDS = Counter(nltk.corpus.stopwords.words('english'))
if __name__ == '__main__':
print("is" in STOP_WORDS)
... |
def isWordGuessed(secretWord, lettersGuessed):
tester=0
for letterS in secretWord:
if letterS in lettersGuessed:
tester+=1
else:
return False
return True
def getAvailableLetters(lettersGuessed):
list=""
import string
availableL=string.... |
import pyCardDeck
from random import randint
import os
import time
"""<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>"""
class Player:
def __init__(self, name, is_computer):
self.name = name
self.cards = []
... |
import threading
'''
This class reverses each word it receives and appends it to
sentence
'''
class ReverseStrThread(threading.Thread):
def __init__(self, word):
if type(word) is not str:
raise Exception("word is not a string")
self.word = word
threading.Thread.__init__(self)
... |
"""
--- Day 7: The Sum of Its Parts ---
You find yourself standing on a snow-covered coastline; apparently, you landed a little off course. The region is too
hilly to see the North Pole from here, but you do spot some Elves that seem to be trying to unpack something that washed
ashore. It's quite cold out, so you decid... |
import cv2
import numpy as np
img = cv2.imread("resources/Skullz.jpg")
#grayscale
# cv2.cvtColor(img Variable , color change ) -> convert color
# in open cv its not rgb its bgr so we choose bgr2gray
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#blur
# using the GaussianBlur .GaussianBlur(input_img, k_size , )
imgB... |
# web scraping tutorial 1
# using beautiful soup 4
import bs4 as bs
import urllib.request
import re
source = urllib.request.urlopen('https://pythonprogramming.net/parsememcparseface/').read()
# gives the source code
soup = bs.BeautifulSoup(source,'lxml')
print(soup.title)
print(soup.title.string)
#... |
class Item(object):
def __init__(self,name,value,cost):
self.name = name
self.value = value
self.cost = cost
def getName(self):
return self.name
def getValue(self):
return self.value
def getCost(self):
return self.cost
def getDensity(self):
ret... |
#-*- coding:utf-8 -*-
from os import path
from wordcloud import WordCloud
#脚本所在路径
d=path.dirname(__file__)
#Read the whole text.
text=open(path.join(d,'constitution.txt')).read()
#Generate a word cloud image
wordcloud=WordCloud().generate(text)
#Display the generated image:
#the matplotlib way:
import matplotlib.py... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.