text stringlengths 37 1.41M |
|---|
# This is a list
pets = ["doggo", "cat", "iguana"]
# We access list variables by their index, which starts at 0
dog = pets[0]
# If you give a negative INDEX, you access the end of the list
demonSpawn = pets[-1]
# If you want to access a range of values in a list,
# you use a number and a colon : and then end of the ran... |
# store dictionaries in a list +
# make dictionary(ies) +
# delete something on a list +
# add something to a list +
# view everything on the list +
# have a way to quit +
# can't stop won't stop until Q :check +
# MAKE THEM IN FUNCTIONS check in progress +
toDoList = []
def welcomeMessage():
message = """\n
()()... |
""" Remove reactions with a given stoichiometry from a table, writing a new table. """
import argparse
from ast import literal_eval
from table_utilities import read_reaction_table, read_component_table, write_reaction_table
parser = argparse.ArgumentParser(
description='Remove reactions with a given stoichiometry... |
""" Remove reactions from a table that involve given species, writing a new table. """
import argparse
from table_utilities import read_reaction_table, read_component_table, write_reaction_table
parser = argparse.ArgumentParser(
description='Remove reactions from a table that involve certain species, writing a ne... |
"""
Tic Tac Toe Player
"""
import math
import sys
import copy
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns pl... |
# Python Program to find sum of array
# Given an array of integers, find sum of its elements.
arr = [2, 3, 4]
print(sum(arr))
|
import curses
import sys
import time
from pynput import keyboard
from ._widget import Widget
class Button(Widget):
"""
A simple widget to get a input button.
For eg, if the key esc is asigned to it and a appstate,
it will change the appstate to it when the esc key is pressed
"""
... |
list1 = []
list2 = []
list3 = []
def merger_list(first_list, second_list):
mydict = {word:1 for word in first_list}
mydict.update({word:1 for word in second_list})
List = []
for word in mydict:
List.append(word)
return List
while 1:
print("Введите количество строк в 1 списке ")
try... |
f = open('text.txt', 'r')
mydict = {}
for line in f:
words = line.split()
for word in words:
mydict[word] = 1
for word in mydict:
print(word)
wait = input()
|
print ("Hello You!, ik ben Ties Hogenboom")
print ("Wie ben jij?")
naam = input ()
print("Hello, " + naam)
print("Hier zijn wat vragen over mij:")
ans = input ("In welk jaar ben ik geboren? A 2002 B 2003 C 2004")
if ans == "B":
print("Dat is correct ik kom uit 2003!")
else :
print("dit is niet juist")
ans = ... |
import math
from scipy import stats
import numpy
sample_data = [11, 15, 17, 27, 20, 17, 13, 22, 17]
mean = numpy.mean(sample_data)
median = numpy.median(sample_data)
mode = stats.mode(sample_data)
data_range = numpy.ptp(sample_data, axis=0)
sum_squared = sum(sample_data)**2
sum_of_squares = sum([i**2 for i in sample_da... |
import os
import random
def menu():
print("1. one player")
print("2. two players")
selection = input()
if selection == "1":
os.system('clear')
oneplayer()
elif selection == "2":
os.system('clear')
twoplayers()
else:
exit()
def twoplayers():
p1_sc... |
class eseleccion():
def __init__():
pass
# Ejercicio4 Construir un algoritmo
def ejer4(self):
nota=float(input("Ingrese su nota o calificación: "))
if nota>=7:
print(" Su calificacion es:{} APROBADO ".format(nota) )
#Ejercicio5 Calificación de un alumno en... |
def romb(n):
for i in range(n+1):
for _ in range(n-i):
print(' ', end='')
for _ in range(i*2+1):
print('#', end='')
print()
for i in range(n):
for _ in range(i+1):
print(' ', end='')
for _ in range(2*(n-i)-1):
print('#', end... |
# Uses python3
import sys
def lcm_naive(a, b):
for l in range(1, a*b + 1):
if l % a == 0 and l % b == 0:
return l
return a*b
def primes(n):
result = []
# Print the number of two's that divide n
while n % 2 == 0:
result.append(2)
n = int(n / 2)
... |
# В школе решили набрать три новых математических класса.
# Так как занятия по математике у них проходят в одно и то же время,
# было решено выделить кабинет для каждого класса и купить в них новые парты.
# За каждой партой может сидеть не больше двух учеников.
# Известно количество учащихся в каждом из трёх классов.
#... |
# По данному натуральному числу N найдите наибольшую целую степень двойки,
# не превосходящую N. Выведите показатель степени и саму степень.
# Операцией возведения в степень пользоваться нельзя!
# For a given natural number N find the greatest integer power of two,
# not superior to N. Output the exponent and the degr... |
# Пирожок в столовой стоит A рублей и B копеек.
# Определите, сколько рублей и копеек нужно заплатить за N пирожков.
# Программа получает на вход три числа: A, B, N,
# и должна вывести два числа: стоимость покупки в рублях и копейках.
# Pie in the dining room is A rubles and B kopecks.
# Determine how many rubles and ... |
# Дана последовательность натуральных чисел, завершающаяся числом 0.
# Определите, какое наибольшее число подряд идущих элементов
# этой последовательности равны друг другу.
# Given a sequence of natural numbers ending with the number 0.
# Determine what is the largest number of consecutive elements
# of this sequen... |
# С начала суток часовая стрелка повернулась на угол в α градусов.
# Определите на какой угол повернулась минутная стрелка с начала последнего часа.
# Входные и выходные данные — действительные числа.
# Since the beginning of the day, the hour hand turned at an angle of α degrees.
# Determine the angle turned the... |
# Дано положительное действительное число X.
# Выведите его первую цифру после десятичной точки.
# Given a positive real number X.
# Outputting the first digit after the decimal point.
print('Дано положительное действительное число X.')
print('Вывести его первую цифру после десятичной точки.')
print()
ans = 'y'
wh... |
# Последовательность состоит из различных натуральных чисел
# и завершается числом 0. Определите значение второго
# по величине элемента в этой последовательности.
# Гарантируется, что в последовательности есть хотя бы два элемента.
# The sequence consists of distinct natural numbers
# and ends with the number 0. Dete... |
# С начала суток часовая стрелка повернулась на угол в α градусов.
# Определите сколько полных часов, минут и секунд прошло с начала суток,
# то есть решите задачу, обратную задаче «Часы - 1».
# Запишите ответ в три переменные и выведите их на экран.
# Since the beginning of the day, the hour hand turned at an an... |
# By using list comprehension, please write a program to print the list after removing delete numbers which are
# divisible by 5 and 7 in [12,24,35,70,88,120,155].
target = [12, 24, 35, 70, 88, 120, 155]
new_list = [x for x in target if x % 5 != 0 and x % 7 != 0]
print(new_list)
|
# Write a program that computes the net amount of a bank account based a transaction log from console input.
# The transaction log format is shown as following:
# D 100
# W 200
# ??
# D means deposit while W means withdrawal.
# Suppose the following input is supplied to the program:
# D 300
# D 300
# W 200
# D 100
# Th... |
# A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT
# with a given steps. The trace of robot movement is shown as the following:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# ??
# The numbers after the direction are steps. Please write a program to compute the di... |
# Define a function that can accept an integer number as input and print the "It is an even number"
# if the number is even, otherwise print "It is an odd number".
def print_parity(num):
print("Is is an even number") if num % 2 == 0 else print("It is an odd number")
print_parity(2)
print_parity(4)
print_parity(5) |
# Write a method which can calculate square value of number
def square(x):
return x**2
|
# Please write a binary search function which searches an item in a sorted list. The function should return the index
# of element to be searched in the list.
def binary_search(list, item):
left = 0
right = len(list) - 1
index = -1
while right >= left and index == -1:
middle = int((left + right... |
# Define a class, which have a class parameter and have a same instance parameter.
class Car:
def __init__(self, model):
self.model = model
audi = Car('audi')
print(audi.model) |
# Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th
# row and j-th column of the array should be i*j.
# Note: i=0,1.., X-1; j=0,1,??Y-1.
# Example
# Suppose the following inputs are given to the program:
# 3,5
# Then, the output of the program should b... |
sumofFactors = 0
def findFactors(number):
factors = [1]
for i in range(2, number//2 + 1):
if (number % i == 0):
factors.append(i)
return factors
def sumFactors(factors):
sumofFactors = 0
for i in range(0, len(factors)):
sumofFactors += factors[i]
return sumofFactors
def checkNumber(sumofFactors, numb... |
#!/usr/bin/env python2.7
# DONT READ COMMENTS
import RPi.GPIO as GPIO
from time import sleep
import sys
board_type = sys.argv[-1]
GPIO.setmode(GPIO.BCM) # initialise RPi.GPIO
GPIO.setup(25, GPIO.OUT) # 22 normal input no pullup
if board_type == "m":
print... |
num1=int(raw_input("Dime un numero: "))
num2=int(raw_input("Dime otro numero: "))
suma=num1+num2
resta=num1-num2
print "La suma es:", suma
print "La resta es:", resta
|
#!/usr/bin/python3
'''THIS IS MY FUNCTION
THAT WILL ADD TWO NUMBERS
IT WILL TAKE TWO INTEGER
ARGS a, b
it's name is simple function'''
def add_integer(a, b=98):
''' add_integer simple function
args
a, b'''
try:
if isinstance(a, float):
raise TypeError
except TypeError:
... |
#!/usr/bin/python3
def replace_in_list(my_list, idx, element):
z = len(my_list)
for i in range(0, z):
if idx == i:
my_list[i] = element
return (my_list)
elif idx < 0:
return (my_list)
elif idx > z - 1:
return (my_list)
|
#!/usr/bin/python3
"""
Module that contains function
"""
def read_file(filename=""):
"""function read_file
Args:
filename
"""
with open(filename, 'r') as f:
data = f.read()
print(data, end='')
|
# def getMissingNo(A):
# n = len(A)
# total = (n+1)*(n+2)/2
# sum_of_A = sum(A)
# return total - sum_of_A
# def getmissingno(array):
# arraylength = len(array)
# total = (arraylength+1)*(arraylength+2)/2
# sumarray = sum(array)
# return total - sumarray
def getmissingno(anarray):
f... |
import translators as ts
import tkinter
from tkinter import filedialog
def choose_files():
root = tkinter.Tk()
root.withdraw()
root.attributes('-topmost', True)
root.title("Choose Text Files")
files = filedialog.askopenfilename(title='Choose Text File', filetypes=(('Plain Text', '*.txt'), ('List Fi... |
# 코딩테스트 연습 - 스택/큐 - 주식가격
prices = [1, 2, 3, 2, 3]
def solution(prices):
answer = []
# prices 배열의 현재값을 위한 변수 i
for i in range(len(prices)):
sec = 0
# i와 미래를 비교하기 위한 v
for v in range(i+1,len(prices)+1):
if v == len(prices): # 총 시간과 반복이 일치할 경우... |
"""
- 백준 - 동적계획법 - 계단오르기
- URL : https://www.acmicpc.net/problem/2579
- 문제 풀이 과정 : 한 번에 한 계단, 혹은 두 계단씩 오를 수 있으므로 매번 계단수 마다의 최대값을 answer list에 저장.
for 문으로 전전 최댓값 + 현재 계단점수 와 전 최댓값을 비교하여 더 큰 값을 저장
마지막 계단은 무조건 밟아야 하므로, input list를 reverse시켜 무조건 밟고 시작하기
"""
def solution(floor)... |
def getkey():
list1=[]
while True:
a=input("请输入键:")
if a == "" :
break
list1.append(a)
return list1
def getvalue(list0):
i=len(list0)
list1=[]
for k in range(i):
a=input("请输入值:")
list1.append(a)
return list1
def makedic(list1,list2):
... |
#Case 7: Please write a program which count and print the numbers of each character in a string input by console.
# Example: If the following string is given as input to the program:
# abcdefgabc
# Then, the output of the program should be:
# a,2
# c,2
# b,2
# e,1
# d,1
# g,1
# f,1
dic = {}
... |
# Case: Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0)
# Example:
# If the following n is given as input to the program:
# 5
# Then, the output of the program should be:
# 3.55
n=int(input("Enter a number: "))
sum=0.0
for i in range (1,n+1):
sum+=flo... |
# Write a code which accepts a sequence of words as input and prints the words in a sequence after sorting them alphabetically.
# Hint: In case of input data being supplied to the question, it should be assumed to be a console input.
my_str=input("Enter your word: ")
words=my_str.split()
words.sort()
for wor... |
"""
A Singleton that controls the image and sound files. Uses python csv.
"""
import csv
# The FileManager's job is to handle all file input
class FileManager():
# Inner class - This is where the implementation goes!
class __FileManager:
def __init__(self):
# Two separate di... |
def odd_even():
for x in range(1, 2001):
iteration = "Number is " + str(x) + ". "
if (x % 2 == 0):
even_num = iteration + "This is an even number."
print even_num
else:
odd_num = iteration + "This is an odd number."
print odd_num
odd_even()
def multiply(lst, num):
new_lst = []
for x in lst:
new... |
def multiples():
for count in range(5, 1000):
if (count % 2 != 0):
print count
else:
passdef find_characters(arr, character):
multiples()
def multiples_five():
for count in range(5, 1000005):
if (count % 5 == 0):
print count
else:
pass
multiples_five()
## Sum List
a = [1, 2, 5, 10, 255, 3]
de... |
__author__ = 'edfeng'
def sum_of_multiples(n):
return sum([i for i in xrange(1, n) if i % 3 == 0 or i % 5 == 0]) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Program de Criptografia Cifra de Vigenère
def val_cod(key_val, char_val):
val_final = (key_val + char_val)
if (val_final > 255):
return (val_final%255)
return val_final
def input_file(nome_arq):
with open(nome_arq, "rb") as f:
byte = f.read()
info = [by... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1:
... |
class Stack(object):
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
class Solution(object):
... |
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
arrays = s.split()
if not arrays:
return 0
last = s.split()[-1]
return len(last)
s = Solution()
print s.length... |
# Step 1: Make all the "turtle" commands available to us.
import turtle
# Step 2: create a new turtle, we'll call him bob and make him look like a turtle
bob = turtle.Turtle()
bob.shape("turtle")
# Step 3: lets make Bob use a blue pen
bob.color("blue")
# Lets draw a star!
for i in range(3):
bob.forwa... |
# 最大・最小ヒープ
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_9_B&lang=jp
import sys
def max_heapify(array, root_index):
left_index = root_index * 2
right_index = left_index + 1
max_index = root_index
# 検索対象となっている節において最も大きい値をルートとする
if left_index < len(array) and array[left_index] > a... |
# https://atcoder.jp/contests/abc158/tasks/abc158_a
def main():
s = input()
if s.__contains__("A") and s.__contains__("B"):
print("Yes")
else:
print("No")
if __name__ == '__main__':
main()
|
import re
import sys
def main():
s = input()
p = re.compile(r'([A-Z][a-z]*[A-Z])+?')
words = p.findall(s)
words = list(map(lambda x: x.lower(), words))
words.sort()
out = sys.stdout
for w in words:
out.write("%s%s%s" % (w[0].upper(), w[1:-1], w[-1].upper()))
out.flush()
if __... |
# 二分探索木: 挿入
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_8_A&lang=jp
import sys
class Node(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def insert(root, v):
if root is None:
root = Node(v... |
# https://atcoder.jp/contests/abc148/tasks/abc148_d
def main():
num = int(input())
origin = [int(i) for i in input().split(" ")]
break_count = 0
want = 1
satisfy = False
for b in origin:
if b == want:
want += 1
satisfy = True
continue
else:
... |
from textblob import TextBlob
a = input("Masukkan kata : ")
print("Kata inputan " + str(a))
b = TextBlob(a)
print("Kata perbaikan :" + str(b.correct()))
|
from tkinter import*
root =Tk()
label1= Label(root,text = "Label 1")
label2= Label(root,text = "Label 2")
label3= Label(root,text = "Label 3")
label1.grid(row = 0,column = 0)
label2.grid(row = 0,column = 1)
label3.grid(row = 1,column = 0)
root.mainloop()
|
from tkinter import*
import random
root = Tk()
canvas= Canvas(root,width = 300, height = 300)
canvas.pack()
def randomRects(num):
for i in range(0,num):
x1 = random.randrange(150)
y1 = random.randrange(150)
x2 = x1 + random.randrange(150)
y2 = y1 + random.randrange(150)
... |
a = int(input())
for i in range(a):
b=int(input())
q=0
for j in range(b):
q+=0.5
q=int(q*2)
print(q)
|
import math
a=[int(a) for a in input().split()]
for q in range(a[0]):
if int(input())<=math.sqrt(a[1]**2+a[2]**2):
print("DA")
else:
print("NE")
|
from typing import List, Union
Number = Union[int, float]
"""
1) Termine os métodos calcula_juros() e saque(valor) da
classe ContaPoupanca
2) Termine o método calcula_juros() da classe ContaCorrente
3) Adicione um atributo à classe Conta chamado _operacoes:
self._operacoes = []
Ele servirá para guar... |
'''
Douglas Byfield
'''
def hello():
print("ECSE3038 - Engineering IoT Systems")
hello()
def validatePassword(psword):
alnum, num = 0, 0
if len(psword) >= 8 and psword.isalnum():
for val in psword:
try:
if isinstance(int(val), int):
num += 1... |
class Program:
def __init__(self, numsList):
self.nums = {i: v for i, v in enumerate(numsList)}
self.relBase = 0
def getNum(self, index, mode=1):
"""
:param index: index to read at
:param mode: 0 for position mode, 1 for immediate mode, 2 for relative mode
:retur... |
"""
filename : dashboard.py
Page : Dashboard
This script is responsible for generating plots on dashboard page.
"""
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
from app.controller.envelope_info import list_envelopes
from app.utils.utilities import page_title
def display_stats():
... |
__author__ = 'Dave Sizer <dasizer@gmail.com>'
while 1==1:
try:
WIDTH = int(raw_input('Width?'))
except ValueError:
print 'Not a number!'
continue
CHAR = raw_input('Draw character?')
for i in range(1,WIDTH-1):
for j in range(1, WIDTH-i):
print('... |
class SchoolAdmission:
def __init__(self, file):
self.capacity = int(input())
self.applicants = [line.split() for line in file.read().split('\n')]
self.departments = dict(Biotech=[], Chemistry=[], Engineering=[], Mathematics=[], Physics=[])
self.registered = []
self.place_ap... |
#!/usr/bin/env python
from datetime import datetime, timedelta
import sys
import dateparser
import dateutil.tz
# 0: Monday
# 6: Sunday
START_OF_WEEK = 6
class DateRange(object):
def __init__(self, start=None, end=None):
now = datetime.now(dateutil.tz.tzlocal())
self.week = start == "week"
if self.week:
st... |
import pandas as pd
from fbprophet import Prophet
import matplotlib.pyplot as plt
# ---------------------------
# load and inspect data, which needs to be in a very specific format
# ------
df = pd.read_csv('data/BeerWineLiquor.csv')
# df.rename(columns={'date':'ds', 'beer':'y'}, inplace=True)
df.columns = ['ds','... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.layers import LSTM
from tensorflow.keras.preprocessing.sequence import TimeseriesGenerator #data preprocessing
# enconding
from sklear... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math # for squared root calculation
# -------------------------
# REINFORCEMENT LEARNING
# UCB - upper confidence bound
# example: advertising team sends many different ads to promote an SUV; we need to register if a specific user will cl... |
class Node():
#Node definition for use in Doubly Linked List implementation
def __init__(self, data, prev=None, next=None):
self.data = data
self.prev = None
self.next = None
#https://www.tutorialspoint.com/python_data_structure/python_advanced_linked_list.htm
class DoublyLinkedList():
... |
my_favorite_toy = "Giffy"
guess= " "
guess_count = 0
guess_limit = 5
out_of_guesses = False
print("Welcome to My Favorite Toy Guessing Game!")
while guess != my_favorite_toy and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("Enter your guess: ")
guess_count +=1
else:
... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
p1 = 6000
p2 = 3000
p3 = 1000
total = p1+p2+p3
iva = .16
# respuestasi = {'si'}
R= input(" Desea Iva desglosado ( Si/No) ")
print("-"*79)
print("{:40} | {:6}".format("Productos", "Precio"))
print("-"*79)
print("{:40} | {:>10.2f}".format("Lap", p1,))
print("{:40} | {:10.2f}... |
import argparse
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
#We must specify both shorthand ( -n) and longhand versions ( --name)
ap.add_argument("-n", "--name", required=True, help="Enter user name")
ap.add_argument("-c", "--country", required=True, help="Enter country ... |
class Credentials:
'''
This is class that stores all the credentils of each user
and hence allows the user to access the information once they are logged in
'''
def __init__ (self,user_name, credential_name , credential__password):
self.user_name = user_name
self.credential_name =cre... |
#Problem Link - https://leetcode.com/problems/friend-circles/
class Solution:
def findCircleNum(self, M):
N = len(M)
visited = [0] * N
circle = 0
queue = []
for index in range(N):
if not visited[index]:
queue.append(index)
circle +=... |
"""
Полиморфизм - возможность объектов с одинаковой спецификацией иметь различную реализацию.
Все объекты имеют один и тот же метод в классе, но вычисляется он по-разному. И теперь можно проходить по всем этим
объектам в цикле и выполнять для каждого объекта свое действие, вызывая лишь один метод.
!!!А что если метод e... |
"""
Любой экземпляр класса без переопределения метода __bool__ возвращает True.
Любое число отличное от нуля - возвращает True. 0 - возвращает False.
Строки, кортежи, списки - если они пустые, то они возвращают False. Если они что-то в себе содержат, то - True.
Чтобы экземпляр класса возвращал нам при необходимости нуж... |
# This code is for fully educational purposes and it implements the simulated annealing AI algorithm
# for more information please visit: https://en.wikipedia.org/wiki/Simulated_annealing
import numpy
import time
import random
NEIGHBORHOOD_MAX = 40
NEIGHBORHOOD_MIN = 0
T_MAX = 100
T_MIN = 0.01
def f(x):
assert... |
s = input("Input a string: ")
digits = ""
for i in s:
if i.isdigit():
digits += i
print(digits)
|
cost = float(input("Input the loan amount: "))
month = 0
payment = 50.0
remainder = cost
if cost <= 1000:
irate = 0.015
else:
irate = 0.02
while True:
month += 1
interest = remainder * irate
remainder += interest -payment
if remainder > 0:
print("Month:", month, "Payment:", round(payme... |
# palindrome function definition goes here
def palindrome(mystr):
mystr = mystr.lower()
newstr = ""
for i in mystr:
if i.isalpha():
newstr += i
if newstr == newstr[::-1]:
return True
else:
return False
in_str = input("Enter a string: ")
# call the ... |
top_num = int(input("Upper number for the range: ")) # Do not change this line
for i in range (1,top_num+1):
summa=0
for j in range(1,i):
if (i % j) == 0:
summa += j
if i == summa:
print(i) |
num1 = int(input("Input a number: "))
num2 = int(input("Input a number: "))
if num1 > num2:
print(num1, "is greater")
elif num2 > num1:
print(num2, "is greater")
else:
print("The numbers are equal") |
celsius = int(input("Input temperature in celsius: "))
farenheit = int(celsius * 9/5 + 32)
print(celsius,"°C is", farenheit, "°F") |
num = int(input("Input an int: ")) # Do not change this line
summa = 0
for i in range(1, num+1):
summa += i
print(summa) |
# _*_coding:utf-8_*_
# 创建用户 :chenzhengwei
# 创建日期 :2019/7/12 上午10:39
"""
以升序的形式维护已排列的可变序列
"""
import bisect
list1 = []
bisect.insort(list1, 2)
bisect.insort(list1, 1)
bisect.insort(list1, 8)
bisect.insort(list1, 5)
print(list1)
print(bisect.bisect_right(list1, 2)) #
print(list1)
print(bisect.bisect_left(list1, 2... |
# _*_coding:utf-8_*_
# 创建用户 :chenzhengwei
# 创建日期 :2019/7/10 下午2:42
"""
python自省 在运行时能够获得对象的类型。
type(),判断对象类型
dir(), 带参数时获得该对象的所有属性和方法;不带参数时,返回当前范围内的变量、方法和定义的类型列表
isinstance(),判断对象是否是已知类型
hasattr(),判断对象是否包含对应属性
getattr(),获取对象属性
setattr(), 设置对象属性
"""
# type
print(type(123)) # <class 'int'>
... |
# open the input file and read the contents
text_file = open('curiosity_shop.txt')
text = text_file.read()
# find the position of the period which separates the sentences
period_position = text.find('.')
# extract the first sentence and write it to an output file
first_sentence = text[0:period_position+1]
fi... |
year = int(input("Enter Year: "))
if year % 4 == 0 & year % 100 != 0:
print(year, "yes")
elif year % 100 == 0:
print(year, "no")
elif year % 400 ==0:
print(year, "yes")
else:
print(year, "no")
|
import unittest
from oop import *
class oopTest(unittest.TestCase):
def test_person_instance(self):
tenant1 = Tenant('Sue', 'Jackson', 10000)
owner1 = Property_owner('Ian', 'Smith', [tenant1])
self.assertIsInstance(owner1, Person, msg='The object should be an instance of the `Person` clas... |
class Order:
"""
Initiated a new order for the store
"""
def __init__(self, order_number, product_id, item_type, name, product_details, factory, quantity, holiday):
"""
Construct a new order
:param order_number: str
:param product_id: str
:param item_type: str
... |
from enum import Enum
class Fabric(Enum):
"""
The Fabric of the stuffed animal, can either be Linen, Cotton or Acrylic.
"""
LINEN = "Linen"
COTTON = "Cotton"
ACRYLIC = "Acrylic"
def __str__(self):
"""
String method of the class.
:return: str
"""
ret... |
"""
Implements the observer pattern and simulates a simple auction.
"""
import random
class Auctioneer:
"""
The auctioneer acts as the "core". This class is responsible for
tracking the highest bid and notifying the bidders if it changes.
"""
def __init__(self):
"""
Initialize an ... |
#!/usr/bin/env python
from pleeplee.geometry import (Point, Triangle, rotateAngle, rotateVector,
angleBetween2Vects, PRECISION)
from pleeplee.utils import Color
from math import sqrt
# Test the Point class
def test_point_distance():
point1 = Point(2.0, 4.5)
point2 = Point(3.4, 6.7)
assert point1.d... |
'''
in terminal:
python spheres.py
'''
import random
import math
import scipy
from scipy import stats
#return radius (in angstroms) of a sphere representing a protein
# of randomly generated chain length betwen 80-500 residues
def return_sphere():
l = random.randint(80, 500)
w = l*110
r = 10*(0.066*(w**(1./3)))... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.