text stringlengths 37 1.41M |
|---|
import math
x = input()
if x == '1':
a, b, c = map(float, [input(), input(), input()])
p = ((a+b+c)/2)
s = math.sqrt(p*(p - a) * (p - b) * (p - c))
print("S = ", s)
elif x == '2':
a1, a2, b1, b2, c1, c2 = map(int, input("Введите a1, a2, b1, b2, c1, c2 через пробел: ").split())
a = math.sqrt((a1 - b1... |
def bmi(weight:float, height:float):
height /= 100
return weight / (height * height)
def print_bmi(bmi:float):
if (bmi < 18.5):
print("Underweight")
elif (bmi >= 18.5 and bmi < 25.0):
print("Normal")
elif (bmi >= 25.0 and bmi < 30.0):
print("Overweight")
else:
pri... |
dic = {1:"first",2:"second"}
print(dic.get(1))
print(dic.get("没有","没找到"))
print(11 // 2)
#递归阶乘
def plus(n):
if n == 1:
return 1
return n * plus(n-1)
s = plus(4)
print(s)
#斐波拉切数列
def feibolaqie(n):
if n == 1:
return 1
elif n == 2:
return 1
else:
r... |
def fs(n):
return n * n
a = fs(3)
print(a)
b = lambda n : n * n
ret = b(3)
print(ret)
x = lambda a ,b : a + b
def co(x,y):
return x ,y
print(co(2,5))
x = lambda a,b : (a,b)
print(x(1,2))
x = lambda a,b:(a,111)
print(x(2,12))
two = lambda a,b : 2,4 #这是两部分
print(two) #(<function <lambda> at 0x0... |
def interest(money,rate):
for i in range(len(money)):
money[i] = money[i] * (1 + rate)
return money
def main():
amount = [1000,2000,3000,4000]
rate = 0.01
a = interest(amount,rate)
print(amount)
print(a)
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function,
unicode_literals, annotations)
def outer(num1):
def inner_increment(num1): # Hidden from outer code
return num1 + 1
num2 = inner_increment(num1)
print(num1, n... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function,
unicode_literals)
import datetime
# Create a program that asks the user to enter their name and their age.
# Print out a message addressed to them that tells them the year that
# t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Interactive Dictionary in Python"""
from __future__ import (division, absolute_import, print_function,
unicode_literals)
import os
import json
from difflib import get_close_matches
# Get File Directory
WORK_DIR = os.path.dirname((os.path.realpa... |
# All the libraries we need for KNN
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
# This is used for our dataset
from sklearn.datasets import load_breast_cancer
# =============================================================================
# We are using sklear... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Men Restroom Algorithm"""
from __future__ import (division, absolute_import, print_function,
unicode_literals)
import random
import time
import threading
import os
class Menpeeing:
def __init__(self,
stalls=10,
... |
"""
Markdown.py
0. just print whatever is passed in to stdin
0. if filename passed in as a command line parameter,
then print file instead of stdin
1. wrap input in paragraph tags
2. convert single asterisk or underscore pairs to em tags
3. convert double asterisk or underscore pairs to strong tags
"""
impo... |
def mult(a, b):
if b == 1:
return a
else:
return a + mult(a, b-1)
# Test case
print(mult(2, 3))
print(mult(10, 34))
|
s = "abcdefghi"
for index in range(len(s)):
if s[index] == 'i' or s[index] == 'u':
print('There is an i or a u')
for char in s:
if s[index] == 'i' or s[index] == 'u':
print('There is an i or a u')
|
cube = float(input("Enter the number to find the cube root: "))
epsilon = 0.01
num_guesses = 0
low = 0
high = max(1.0, cube)
guess = (high + low)/2.0
def diff(cube, guess):
guess_cube = abs(guess**3)
if (cube > guess_cube):
return (cube - guess_cube)
else:
return (guess_cube - cube)
whi... |
#!/usr/bin/env python3
# Para cambiar el limite de recursion en Python
import sys
# Se define la funcion fibonnacci mediante recursividad y la retorna
def fibonacci_recursivo(n):
if n == 0 or n == 1:
return 1
return fibonacci_recursivo(n - 1) + fibonacci_recursivo(n - 2)
# Para memorizacion se utili... |
import requests
from lxml import html
import calendar
from itertools import chain
import datetime
# Constants
# -------------------------------------------
MONTH_TO_NUM = {name: num for num, name in enumerate(calendar.month_abbr) if num}
# Helper functions
# --------------------------
def get_date(date_element):
... |
from string import ascii_uppercase as a
from matrix_edits import matrix_to_alpha
a_len = len(a) # length of alphabet: 26
ext = 8 # number of spaces: ptx uses 8
# First column in reverse alphabetical order, will be reversed back later
c = list(reversed(range(a_len + ext)))
r = list(range(a_len + ext - 1))
# Make a ... |
class Student:
def __init__(self, name, surname, gender):
self.name = name
self.surname = surname
self.gender = gender
self.finished_courses = []
self.courses_in_progress = []
self.grades = {}
def rate_lecturer(self, lecturer, course, grade):
if isinstanc... |
""""
This class holds two dictionaries with keys being words in the puzzle and values being the Cell where that word
begins. There is a dictionary for across words and another for down words. The dictionaries also serve as lists
of the across and down words currently in the puzzle.
"""
class CrosswordRepresentation:
... |
# Procurada a intersecçao nas sequencias geradas, se nao achado e aumentado o tamanho da sequencia ate ser econtrado
tam = 10000
achou = 0
while(not achou):
T = [] #Vetores que armazenam a sequencia
P = []
H = []
for i in range(286,tam): #Obtendo sequencia dos numeros Triangulares
T.append((i*(i-1)/2))
for i... |
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) <= 0:
return 0
length = 0
for i in range(len(s)-1, -1, -1):
if s[i] != ' ':
length += 1
elif length != 0:
... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head:
... |
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
if n==1:
return [[1]]
result = []
for i in range(n):
result.append([0] * n)
idx,idy = 0, 0
total = n * n
directi... |
"""
Given a set of activities to schedule among a large number of lecture halls,
where any activity can take place in any lecture hall. Schedule all the
activities using as few lecture halls as possible
"""
import unittest
import datetime
def assign_halls(activities, halls):
"""
Assigns provided activities to give... |
"""
S - set of activities. I-th element of it corresponds to a_i activity and
is represented as a pair (s_i, f_i), where s_i is start time and f_i is end time,
it is assumed that 0 <= s_i < f_i < Inf. It's assumed that activities are sorted
in monotonically increasing order of finish time.
Activities a_i and a_j are c... |
"""Question 5 - Demonstrate how to add widgets into table views
Rather than use delegates for rendering and editing items, it
is sometimes desirable to simply insert widgets into a view
to display static content.
Building Custom UIs with PyQt with Packt Publishing
Chapter 3 - Getting More Out of PyQt’s Model/View ... |
# implementation of heap class
class Heap:
def __init__(self, A):
if (type(A) is not list):
raise TypeError("A type is", type(A) ,", A need be from type 'list'")
else:
self.size = 0
self.A = []
print ("len(A)",len(A))
for i in range(0, len... |
database = [
('a', '1'),
('c', '1'),
('c', '3'),
('d', '3'),
('d', '8'),
('e', '4')
]
names, emails = {}, {}
for name, email in database:
name_entry = names.setdefault(name, [[], False])
email_entry = emails.setdefault(email, [[], False])
name_entry[0].append(email_entry)
email... |
REPLACE = "[name]"
#TODO: Create a letter using starting_letter.txt
#opens invited_names file, and stores the listed names in a variable called 'names'
with open("./Input/Names/invited_names.txt") as names_list:
names = names_list.readlines()
#opens a sample letter that has a placeholder string, & stores as a str... |
######################################################################
# Author: Tradd Schmidt
# Username: schmidtt
#
# Assignment: P0: Final Project
#
# Purpose: Allow a user to input either binary or text into the function and return the ASCII form if it is text with the
# parity bit added on, or the binary wi... |
######################################################################
# Author: Tradd Schmidt TODO: Change this to your names
# Username: schmidtt TODO: Change this to your usernames
#
# Assignment: A3: A Pair of Psychedelic Functional Robotic Turtles
import turtle
def make_turtle():
"""
... |
######################################################################
# Author: Tradd Schmidt
# Username: schmidtt
#
import turtle
wn = turtle.Screen() #Creates Turtle screen
wn.bgcolor("black") #Sets bg color to Aqua
friend = turtle.Turtle()
friend.hideturtle()
friend.speed(0)
... |
class Solution:
def checkRecord(self, s: str) -> bool:
case1=True
case2=True
countabsent=0
for i in range(0,len(s)):
if s[i]=='A':
countabsent=countabsent+1
if countabsent>=2:
case1=False
for i in range(0,len(s)-3+1):
... |
def find_min_max(arg):
arg.sort()
result = [] # Initialise empty list to store the result
biggest = arg[0]
smallest = arg[len(arg) - 1]
if biggest == smallest: # Checking to see if the numbers are the same
result.append(biggest)
return result
else:
result.append(bi... |
# k keans clustering algorithm
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# read data from csv
cust_df = pd.read_csv("sklearn\Cust_Segmentation.csv")
print(cust_df.head())
df = cust_df.drop("Address", axis=1)
print(... |
from copy import copy
FLOOR = "."
EMPTY = "L"
OCCUPIED = "#"
class State:
def __init__(self, data):
self.data = data
def get_adjacent(self, x, y, part_two):
if part_two:
return self.get_visible_adjacent(x, y)
adjacent = [
self.get_seat(x + 1, y),
... |
class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
while k > 0:
a = nums.pop()
nums.insert(0,a)
k -=1
a = Solution()
lis... |
from functools import reduce
def add1(x,y):
return x+y
def add(x, y, f):
return (f(x)+f(y))
def f(x):
return x*x
def is_odd(n):
return n % 2 == 1
print(add(-1, 1, abs))
r = map(f, [1,2,3,4,5,6,7,8,9,10])
print(list(r))
a = reduce(add1, [1,3,5,7,9])
print(a)
b = list(filter(is_odd, [1,2,3,5,8]))
... |
gameBg = [[00,1,2],[10,11,12],[20,21,22]]
for row in gameBg:
print(row)
# ----Proceed to play---
row = int(input("Enter row to change"))
col = int(input("Enter col to change"))
gameBg[row][col] = "x"
for row in gameBg:
print(row)
|
friend_pizzas=['tuna', 'cheese', 'meatlover']
friend_pizzas.append("papperoni")
print("my favorite pizzas are:")
print(friend_pizzas)
friend_pizzas.append("americalover")
print("\nMy friend's favorite pizzas are:")
print(friend_pizzas)
|
name=['ardan', 'excel', 'lamin']
print('we have more space for my friends!\n')
name.insert(len(name),"krisse")
name.insert(len(name),"Cindy")
name.append("bryan\n")
print("im so sorry, you cannot able to join to my place " +name.pop()+"....")
print("im so sorry, you cannot able to join to my place " +name.pop()+"...... |
from pandas import read_csv #to read csv file, csv -> comma separated values
from numpy import set_printoptions #to print precision in accuracy
from sklearn.model_selection import train_test_split #to split train and test from a dataset
from sklearn.ensemble import RandomForestClassifier #importing Random Forest Clas... |
theBoard = {'1': ' ', '2': ' ', '3': ' ', '4': ' ',
'5': ' ', '6': ' ', '7': ' ', '8': ' ',
'9': ' '}
def printBoard(board):
print(board['1'] + '|' + board['2'] + '|' + board['3'])
print('-+-+-')
print(board['4'] + '|' + board['5'] + '|' + board['6'])
print('-+-+-')
p... |
def binary_search(lst, value):
# 所以时间复杂度可以表示O()=O(logn)
n = len(lst)
low, high = 0, n - 1
while low <= high:
mid = (low + high) // 2
if lst[mid] == value:
return True
elif lst[mid] < value:
low = mid + 1
else:
high = mid - 1
return ... |
def linear_search(lst, value):
# 时间复杂度:O(n)
for i in range(len(lst) - 1):
if lst[i] == value:
return True
return False
if __name__ == '__main__':
l = [1, 2, 8, 3]
print(linear_search(l, 2))
|
from heapq import heappush, heappop
def heap_sort(lst):
temp = []
# 入堆
for item in lst:
heappush(temp, item)
# 清空列表
lst.clear()
# 出堆
for i in range(len(temp)):
lst.append(heappop(temp))
l = [1, 2, 3, 4, 0, 9, 2, 3]
heap_sort(l)
print(l)
|
import time
"""若a+b+c=1200,a^2+b^2=c^2,a,b,c都是正整数,求a,b,c的值
枚举法
独立存在解决问题的思路和方法
"""
start = time.time()
for a in range(0, 1001):
for b in range(0, 1001):
c = 1000 - a - b
if a + b + c == 1000 and a**2 + b**2 == c**2 and a*b*c != 0:
print("a=%d,b=%d,c=%d" % (a, b, c))
end = time.time()
pr... |
from heapq import *
def heap_sort(lst):
result = []
# 入堆
for value in lst:
heappush(result, value)
# 出堆
# result2 = []
# for i in range(len(result)):
# result2.append(heappop(result))
# return result2
return [heappop(result) for i in range(len(result))]
print(heap_sor... |
import math
# name = input('please input your name:')
# print('hello,', name)
print(1024 * 768)
a = 100
if a >= 0:
print(a)
else:
print(-a)
print('I\'m ok!')
print('包含中文')
boys = ['tom', 'dog', 'pig']
L = [
['Apple', 'Google', 'Microsoft'],
['Java', 'Python', 'Ruby', 'PHP'],
['Adam', 'Bart', '... |
"""
集合 set frozenset
集合中的元素必须是可散列的,set类型本身是不可散列的,但是frozenset可以。因此可以创建一个包含不同frozenset的set。
"""
# Demo_3-10, Demo_3-11, Demo_3-12
# 使用集合计算交集
from dis import dis
if __name__ == '__main__':
set_A = {1, 2, 3}
set_B = {1, 2, 4, 5, 6, 7}
print(len(set_A & set_B))
print(len(set_A.intersection(set_B)))
... |
"""
匿名函数
lambda
Python简单的句法限制了lambda函数的定义体只能使用纯表达式
lambda函数的定义体中不能赋值,也不能使用while和try等Python语句
lambda表达式重构秘笈如果使用lambda表达式导致一段代码难以理解,Fredrik Lundh建议像下面这样重构。
(1)编写注释,说明lambda表达式的作用。
(2)研究一会儿注释,并找出一个名称来概括注释。
(3)把lambda表达式转换成def语句,使用那个名称来定义函数。
(4)删除注释。
"""
if __name__ == '__m... |
"""
collections.abc模块中有Mapping和MutableMapping这两个抽象基类,
它们的作用是为dict和其他类似的类型定义形式接口
标准库里的所有映射类型都是利用dict来实现的
只有可散列的数据类型才能用作这些映射里的键
可散列的数据类型:
这个对象的生命周期中,它的散列值是不变的
而且这个对象需要实现__hash__( )方法
可散列对象还要有__eq__( )方法,这样才能跟其他键做比较
原子不可变数据类型(str、bytes和数值类型)都是可散列类型,
frozenset也是可散列的,因为根据其定义,frozenset里只能容纳可散列类型
... |
import sys
def minElement(a,n):
l=len(a)
min=a[n]
pos=n
for i in range(n+1,l):
if min>a[i]:
min=a[i]
pos=i
return pos
def selectSort(a):
l=len(a)
for i in range(0,(l-1)):
min=a[i]
pos=minElement(a,i+1)
if a[pos]<min:
a[i]^=a[pos]
a[pos]^=a[i]
a[i]^=a[pos]
print(a)
def main(... |
#!/usr/bin/env python3
# display a welcome message
print("Welcome to the Future Value Calculator")
print()
choice = "y"
while choice.lower() == "y": #A while loop that continues as long as the user enter "y" or "Y" using the "lower string method".
# Get input or "entry" from the user and perform "data v... |
from tic_tac_toe import TicTacToe
import numpy as np
import unittest # importing the unittest module
class TestTicTacToe(unittest.TestCase):
def test_init(self):
'''
test_init test case to test if the object is initialized properly
'''
pass
def test_victory_condition_rows(self)... |
"""
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
"""
class Solution:
def isSymmetrical(self, pRoot):
# write code here
#循环判断左子树的根节点和右子树的根节点的值是否相同
if not pRoot:
return True
else:
return self._isSymmetrical(pRoot.left,pRoot.right)
def _isSymmetrica... |
"""
#1, 暴力解 时间复杂度 oo(n^2)
ACE 不了
"""
# class Solution:
# def maxArea(self, height):
# if not height:
# return 0
# max_num = 0
# for i in range(len(height)):
# for j in range(i+1,len(height)):
# weight = j - i
# height1 = height[i]
# ... |
#一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
def FindNumsAppearOnce( array):
dic = {}
for num in array:
dic[num] = dic.get(num, 0) + 1
for num, count in dic.items():
if count == 1:
return num
if __name__ == '__main__':
print(FindNumsAppearOnce([1,2,3,3,4,4,5,5,6,... |
#在一个长度为n的数组里的所有数字都在0到n-1的范围内。
# 数组中某些数字是重复的,但不知道有几个数字是重复的。
# 也不知道每个数字重复几次。请找出数组中任意一个重复的数字。
# 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
#用字典就解决了。
def duplicate( numbers, duplication):
dic = {}
flag = 0
for num in numbers:
if num not in dic:
dic[num] = 1
else:
... |
def replaceSpace(s):
#将字符串中每一个空格替换成 %20 .
new_string = ''
for char in s:
if char != ' ':
new_string+=char
else:
new_string += '%20'
return new_string
if __name__ == '__main__':
print(replaceSpace('We Are Happy'))
|
class Node:
def __init__(self,x):
self.val = x
self.next = None
def Create_LinkList(list_data):
head = Node(0)
p = head
for data in list_data:
temp = Node(data)
p.next = temp
p = p.next
return head
def Print_LinkList(ListNode):
list = []
while ListN... |
"""
输入一个字符串,按字典序打印出该字符串中字符的所有排列。
例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
主要是利用深度优先遍历,
"""
class Solution:
def Permutation(self, ss):
# write code here
temp_perm = []
permuations = []
other_chars = [char for char in ss] # 还没有使用的字符
if ss:
r... |
import Board
import Pieces
import Move
class RulesViolation(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Suicide():
def validate(self, move, board, col, enforceCaptures=True):
# Allow null moves (passes)
if move==Move.PASS:
return True
# Al... |
# -*- coding: utf-8 -*-
class Dog():
def __init__(self, name, age):
""" 初始化类的各个属性"""
self.name = name
self.age = age
def sit(self):
print(self.name.title() + " is now sitting.")
def roll_over(self):
print(self.name.title() + " rolled over.")
class Restaura... |
#!/usr/bin/python3.5
from fractions import Fraction
def convertToFraction(integer, first_block, repeating_block):
number = float(integer + '.' + first_block + repeating_block)
# Move the decimal point directly to the right, and to the left
# then subtract equations:
# decimalptright(x) - decimalptlef... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
def remove_count(text):
pattern = '(.*班).*?'
return re.findall(pattern, text)[0]
if __name__ == '__main__':
print(remove_count('九年级3班2fdf'))
|
from random import random, choice
from functools import reduce
class MyClass(object):
def __init__(self):
print('this is my class')
class Point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def show(self):
print("my location is %d, %d" % (self.x, self.y))
... |
'''
Требуется определить, является ли данный год високосным.
Программа должна корректно работать на числах 1900≤n≤3000.
Выведите "Високосный" в случае, если считанный год является високосным и "Обычный" в обратном случае
'''
n = int(input())
if 1900 <= n <= 3000:
if (n % 4 == 0 and n % 100 != 0) or n % 400 == 0:
... |
'''
Паша очень любит кататься на общественном транспорте, а получая билет, сразу проверяет, счастливый ли ему попался.
Билет считается счастливым, если сумма первых трех цифр совпадает с суммой последних трех цифр номера билета.
Однако Паша очень плохо считает в уме, поэтому попросил вас написать программу, которая пр... |
'''
Напишите программу, принимающую на вход целое число, которая выводит True, если переданное значение попадает
в интервал (−15,12]∪(14,17)∪[19,+∞) и False в противном случае
'''
a = int(input())
if -15 < a <= 12 or 14 < a < 17 or a >= 19:
print('True')
else:
print('False')
|
'''
Напишите программу, которая считывает со стандартного ввода целые числа, по одному числу в строке, и после первого введенного
нуля выводит сумму полученных на вход чисел.
'''
s = int(input())
c = 0
if s == 0:
print(c)
else:
while s != 0:
c += s
s = int(input())
print(c)
|
goods = []
features = {'name': 'Введите название товара',
'price': 'Введите цену товара',
'quantity': 'Введите количество товара',
'unit': 'Введите единицу измерения'}
number = 1
for i in goods:
goods.append(number, features)
print(goods)
|
city = "Kazan"
street = "Lenina"
house_number = 55
apart_number = 22
print(city)
print(street)
print(house_number)
print(apart_number)
city = input("Заполните, пожалуйста, адрес, по которому Вы проживаете:\n 1.Назовите город, в котором Вы проживаете:\n")
street = input("2.Назовите улицу:\n")
house_number = input('3.Но... |
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print(f"Copying from {from_file} to {to_file}")
# opens to_file and makes it writable while opening the from_file to read from
(open(to_file, 'w').write(open(from_file).read()))
print(f"The input file is {len(from_file)} bytes long")
... |
# creates variables
people = 40
cars = 30
trucks = 25
# if statment
if cars > people:
print("We should take the cars.")
# elif = else if
elif cars < people:
print("We should not take the cars.")
# if none of the above options print this
else:
print("We can't decide.")
if trucks > cars:
print("That's t... |
class Solution(object):
def isSymmetric(self, root):
def t(l, r):
if l and r and l.val == r.val:
return t(l.right, r.left) and t(l.left, r.right)
else:
return l==r
if not root:
return True
elif root.left and root.right and r... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Problem 103. Binary Tree Zigzag Level Order Traversal
Given a binary tree, return the zigzag level order traversal of its nodes' values.
(ie, from left to right, then right to left for the next level and alternate between).
"""
__author__ = "Haobo Gu"
__email__ = "ha... |
class Solution(object):
def singleNumber(self, nums):
"""
Given an array of integers, every element appears three times except for one. Find that single one.
"""
"""
One Line Solution:
Use set(), set() can get a set(without same number).
For example: list = [... |
class Solution(object):
def searchInsert1(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
i = 0
l = len(nums)
while nums[i] < target and i < l-1:
i += 1
if nums[i] < target:
return l
... |
#!/usr/bin/python3
#t is the number of years; p is principle; r is annual interest rate
#if the annual interest rate is 10%, input 10 in command line
#at the command line, the enter order is t p r
import sys
import math
t = float(sys.argv[1])
p = float(sys.argv[2])
r = float(sys.argv[3])
amount = p*math.exp(t*r/100)
p... |
days_per_month = {
'1': 31,
'2': 28,
'3': 31,
'4': 30,
'5': 31,
'6': 30,
'7': 31,
'8': 31,
'9': 30,
'10': 31,
'11': 30,
'12': 31
}
def date_validate(month, day):
"""
This function makes sure that the date is valid
according to the month an... |
import time
import math
def main():
i = 2
target = 500
num_divisors = 0
while num_divisors < target:
num_divisors = len(divisors_of(get_triangle_num(i)))
if i % 500 == 0:
print(f"For triangle number {get_triangle_num(i)} we get {num_divisors} divisors")
i += 1
e... |
import turtle
t = turtle.Turtle()
t.shape('turtle')
def drawit(x, y) :
t.up()
t.goto(x, y)
t.down()
t.begin_fill()
t.color("green")
square(50)
t.end_fill()
def square(length) :
for i in range(4) :
t.forward(length)
t.right(90)
s = turtle.Screen()
s.onscreenclick(drawi... |
PI = 3.141592
class Circle :
def __init__(self, radius) :
self.radius = radius
def calcPerimeter(self) :
return self.radius * 2 * PI
def calcArea(self) :
return self.radius **2 * PI
circle = Circle(100)
print("반지름 :", circle.radius)
print("원의 면적 :", circle.calcArea())
print("... |
import random
options = ["왼쪽", "중앙", "오른쪽"]
auto = random.choice(options)
where = input("어디를 수비하시겠어요(왼쪽, 중앙, 오른쪽)? ")
if auto == where :
print("수비에 성공하였습니다.")
else :
print("페널티 킥이 성공하였습니다.") |
import turtle
t = turtle.Turtle()
t.shape('turtle')
while True :
order = input("명령을 입력하시오 : ")
if order == "l" or order == "left":
t.left(90)
t.forward(100)
elif order == "r" or order == "right" :
t.right(90)
t.forward(100)
elif order == "q" or order == "quit" :
... |
from tkinter import *
window = Tk()
w = Label(window, text = "박스 #1", bg = "red", fg = "white")
w.place(x = 0, y = 0)
w = Label(window, text = "박스 #2", bg = "green", fg = "black")
w.place(x = 20, y = 20)
w = Label(window, text = "박스 #3", bg = "blue", fg = "white")
w.place(x = 40, y = 40)
window.mainloop() |
from tkinter import *
from PIL import ImageTk, Image
def change_img() :
path = inputBox.get()
img = ImageTk.PhotoImage(Image.open(path))
imageLabel.configure(image = img)
imageLabel.image = img
window = Tk()
photo = ImageTk.PhotoImage(Image.open("wl.gif"))
imageLabel = Label(window, image = photo)
im... |
num = int(input("원하는 단은 : "))
for i in range(1, 10) :
print(num, "*", i, "=", i*num)
|
import turtle
import random
screen = turtle.Screen()
front = "front.gif"
back = "back.gif"
screen.addshape(front)
screen.addshape(back)
t = turtle.Turtle()
coin = random.randint(0,1)
if coin == 0:
t.shape(front)
t.stamp()
else :
t.shape(back)
t.stamp() |
import turtle
t = turtle.Turtle()
t.color("red")
t.shape('turtle')
n = 0
while n < 10 :
t.forward(100)
t.right(135)
t.forward(141)
t.right(135)
t.forward(100)
t.right(90)
t.left(10)
n += 1
turtle.done()
|
import turtle
import math
t = turtle.Turtle()
t.shape('turtle')
for i in range(360) :
sin_x = math.sin(math.pi * i / 180.0)
t.goto(i, sin_x * 100) |
import turtle
t = turtle.Turtle()
t.shape('turtle')
shape = turtle.textinput("", "도형을 입력하시오 : ")
if shape == "사각형" :
width = int(turtle.textinput("", "가로 : "))
height = int(turtle.textinput("", "세로 : "))
t.forward(width)
t.left(90)
t.forward(height)
t.left(90)
t.forward(width)
t.left(... |
radius = int(input("반지름을 입력하시오 : "))
area = 3.14 * radius * radius
print("반지름이 ", radius, "인 원의 넓이 = ", area) |
total = 0
filename = input("파일 이름을 입력하세요 : ")
infile = open(filename, "r")
for line in infile :
line = line.rstrip()
word_list = line.split()
for word in word_list :
total += len(word)
print("파일 안에는 총 " + str(total) + "개의 글자가 있습니다.") |
import random
import turtle
color = ["yellow", "red", "purple", "blue"]
def draw_square(x, y, color) :
t.up()
t.goto(x, y)
t.down()
t.color('black', color)
t.begin_fill()
for i in range(4) :
t.forward(100)
t.right(90)
t.end_fill()
t = turtle.Turtle()
t.shape('turtle')
for ... |
import turtle
data = [120, 56, 309, 220, 156, 23, 98]
def drawBar(height) :
t.begin_fill()
t.left(90)
t.forward(height)
t.write(str(height))
t.right(90)
t.forward(40)
t.right(90)
t.forward(height)
t.right(90)
t.forward(40)
t.right(180)
t.forward(40)
t.end_fill()
t ... |
import turtle
t = turtle.Turtle()
t.shape("turtle")
s = turtle.textinput("", "몇각형을 원하시요? ")
n = int(s)
s = turtle.textinput("", "한변의 길이를 원하시나요? ")
length = int(s)
for i in range(n):
t.forward(length)
t.left(360/n)
turtle.done() |
def sum(num1, num2) :
return num1 + num2
def sub(num1, num2) :
return num1 - num2
def mul(num1, num2) :
return num1 * num2
def div(num1, num2) :
return num1 / num2
num1 = int(input("첫 번째 숫자 : "))
num2 = int(input("두 번째 숫자 : "))
print(str(num1) + " + " + str(num2) + " = ", sum(num1, num2))
print(str... |
#Adriana Avalos Vargas
#Lets call de modules
#Module for paths
import os
# Module for reading CSV files
import csv
#- - - - - - - - - - - - - -- - - - - -- - - - - - - -
#Lets fix the path
csvpath = os.path.join('Resources', 'election_data.csv')
#- - - - - - - - - - - - - - - - - - - - - - - - - --
#A counter to co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.