text stringlengths 37 1.41M |
|---|
'''
Created on Feb 4, 2016
@author: sumkuma2
'''
class MyString():
def reverse(self,some_seq):
"""
Input: Sequence
output: Sequence:
reversed version
"""
return some_seq[::-1]
def is_palindrom(self,some... |
def separate_categories(invoice_lines: dict):
"""
This function separates categories and counts their prices. Decimal euros are converted into integer cents.
:param invoice_lines: dictionary with invoice lines
:return: dictionary with separated categories
"""
categories = {}
for invoice i... |
# -*- coding: utf-8 -*-
"""
Create 3 functions: multiply, add, divide for the calculator class
Each student should make their own branch and work on one of the functions in
the corresponding file.
"""
import multiply as ml
import addition as ad
import division as dv
class Calculator:
def __init__(self):
... |
class NodeData:
"""This class represents a node data of the graph with simple functions."""
def __init__(self, key, pos=None):
self.key = key
self.pos = pos
self.parent = 0
self.tag = 0
def __repr__(self) -> str:
return f"|Key: {self.key}|"
def __lt__(self, oth... |
# Exemplo 1:
produtos = [1, 3, 1, 1, 2, 3]
# resultado = 4
# Os índices (0, 2), (0, 3), (1, 5), (2, 3) formam combinações.
# Exemplo 2:
# produtos = [1, 1, 2, 3]
# resultado = 1
# Os índices (0, 1) formam a única combinação.
def good_combinations(array):
size = len(array)
# result = []
# for x in range(... |
"""Perceba que temos uma coleção de valores
e operações que atuam sobre estes valores,
de acordo com o que foi definido pelo TAD."""
class Array:
def __init__(self):
self.data = []
def __len__(self):
# quando pedido o tamanho do array
# retorne o tamanho de data
return len(se... |
""" Exercício 5: Consulte a forma de se criar um
dicionário chamado de dict comprehension e crie
um dicionário que mapeia inteiros de 3 a 20 para
o seu dobro. Exemplo:
"""
result = {x: x*2 for x in range(3, 20)}
print(result)
|
import sys
print("Please insert the sequence: "+sys.argv[1])
strs = sys.argv[1].split(' ')
v = [int(num) for num in strs]
n = len(v)
# python way of defining a n-dimensional list initialized to 0
sub_sums = [0 for i in range(0, n)]
best = (0, 0)
best_sum = 0
for i in range(0, n):
sub_sums[i] = v[i]
best_end_in... |
import sys
print("$ python3 reversed.py")
print("Please insert n:", sys.argv[1])
n = int(sys.argv[1])
res = 0
i = 0
while n != 0:
res *= 10
res += n % 10
n //= 10
i += 1
print("Result:", res)
|
import sys
print("$ python3 shaker_sort.py")
print("Please insert the array:", sys.argv[1])
strs = sys.argv[1].split(' ')
v = [int(num) for num in strs]
def impl(start, end, step):
sorted = True
for i in range(start, end, step):
if v[i] > v[i+1]:
t = v[i]
v[i] = v[i+1]
... |
# Author - Shivam Kapoor
# This code is written as minimal as possible.
# Github - https://github.com/ConanKapoor/Elliptic_Curve_Implementation.git
# importing libraries
import matplotlib.pyplot as plt
import numpy as np
# Function to plot graph
def Plot_Graph(a,b):
print("\nThe Graph for given equation is : \n")... |
#-*- encoding: utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def genLinkedList(l):
"""
genLinkedList([integers]) -> linkedlist
"""
if l==[]:
return None
else:
length=len(l)
if length==1:
return ListNode(l[0])
else:
head=ListNode(l[0])
h=head
for i in range(... |
import pygame
class Square:
def __init__(self, h, w):
self.h = h
self.w = w
def draw_square(surface):
pygame.draw.rect(surface, (255,255,255), (250, 250, 10,10))
def drawGrid(surface, n_squares, x_dim, y_dim):
delta_x = x_dim//n_squares
delta_y = y_dim//n_squares
x = 0
y = 0
... |
n = int(input("Podaj ile liczb chcesz wprowadzić: "))
wynik = 0;
for i in range(1, n + 1):
wynik = wynik + float(input("Podaj " + str(i) + " liczbe: "))
print("Wynik wynosi", wynik)
# print(float(input("podaj liczbe")) + float(input("podaj liczbe")))
|
should_be_true_graph = {
"s": ["w"],
"w": ["t", "y"],
"y": ["z", "x"],
"x": ["s"],
"z": ["t"],
"t": [], # dest
}
should_be_false = {
"a": ["b"],
"b": ["c"],
"c": ["a"],
}
countmap = {}
path = []
def three_walk(src, dst, length, g):
if src == dst:
return length % 3 =... |
def prime(n):
if n == 2:
return n
elif n>1:
for i in range(n):
if n%2!=0:
return n
else:
pass
|
import re
namestring = False
while namestring is False:
name = input("Hey person, what is your name? ")
x = re.search('[0-9]', name)
if x:
namestring = False
else:
namestring = True
print(name)
|
TICKET_PRICE = 10
SERVICE_CHARGE = 2
tickets_remaining = 100
def calculate_price(number_of_tickets):
return (TICKET_PRICE * number_of_tickets) + SERVICE_CHARGE
while tickets_remaining > 0:
print("There are {} tickets remaining".format(tickets_remaining))
name = input("What's your name? ")
try:
... |
frase = str(input("Digite aqui uma frase:")).lower().replace(" ", "")
if frase == frase[::-1]:
print(" {} é um palíndromo".format(frase))
else:
print(" {} Não é um palíndromo".format(frase)) |
from random import randint
numeros = []
for i in range(5):
numeros.append(randint(0, 100))
tupla = (numeros[0], numeros[1], numeros[2], numeros[3], numeros[4])
print(tupla)
maior = menor = tupla[0]
for i in range(1, len(tupla)):
if tupla[i] > maior:
maior = tupla[i]
if tupl... |
def triangulo(a, b, c):
if a*b*c <= 0:
return False
if a <= abs(b - c) or a > (b+c):
return False
return True
def tipoTriangulo(a, b, c):
if a == b and b == c:
return 0
if a == b or a == c or b == c:
return 1
return 2
tipos = ["Equilatero", "Isosce... |
from time import sleep
text = {
"fecha":"\033[m",
"branco":"\033[30m",
"vermelho":"\033[31m",
"verde":"\033[32m",
"amarelo":"\033[33m",
"azul":"\033[34m",
"roxo": "\033[35m",
"ciano": "\033[36m",
"cinza": "\033[37m",
}
back = {
"fecha":"\033[m",
"branco":"\0... |
inicio = 1
fim = 500
primeiro = inicio + 3 - (inicio%3)
soma = 0
for i in range(primeiro, fim+1, 6):
soma += i
print(soma)
|
"""
026
Faça um programa que leia uma frase pelo teclado e mostre:
Quantas vezes aparece a letra "a"
Em que posição ela aparece a primeira vez
Em que posição ela aparece a última vez
"""
def conta(ref, frase):
return frase.lower().count(ref.lower())
def primeraOcorrencia(ref,frase):
return frase.low... |
nome = input("Informe seu nome: ")
#20 alinhamento esquerda, centralizado e direta
print("Prazer em te conhecer, {:<20}!".format(nome)) #Alinhado a esquerda
print("Prazer em te conhecer, {:^20}!".format(nome)) #Centralizado
print("Prazer em te conhecer, {:>20}!".format(nome)) #Alinha a direita
print("Prazer em te ... |
personagens = ("Eren", "Mikasa", "Armin", "Levi", "Erwin", "Zeke",
"Ichigo", "Orihime", "Yhwach", "Byakuya", "Renji", "Rukia",
"Sakamoto", "Himiko", "Kira", "Oda",
"Kirito", "Asuna", "Shino",
"Elesis", "Lire", "Arme", "Lass", "Ryan", "Ronan", "Amy")
... |
"""
066
Crie um progra que leia vários numeros inteiros pelo teclado.
O programa só vai parar quando o usuário digitar o valor 999.
No final, mostre quantos numeros foram digitados e qual foi a soma entre eles (desocnsiderando 999)
"""
contador = 0
soma = 0
while True:
n = int(input("Digite um numero: "))
... |
"""
071
Crie um programa que simule o funcionamento de um caixa eletrônico.
no início, pergunte ao usuário qual será o valor a ser sacado
e o programa vai informar quantas cédulas de cada valor serão entregues.
obs: considere que o caixa possua cédulas de 50 20 10 e 1
"""
def sacar(valorSaque, cedulasDisponive... |
def escreve(string):
tam = len(string)
tam += 2
linha = "-"*(tam)
print(linha)
print(f" {string}")
print(linha)
string = str(input("Digite sua frase: "))
escreve(string) |
"""
Faça um programa que leia algo pelo teclado e mostre na tela o
seu tipo primitivo e todas as informações possível sobre ele
"""
algo = input("Digite algo: ")
print("Tipo do dado lido: {}".format(type(algo)))
print("Eh numero: {}".format(algo.isnumeric()))
print("Eh alfabetico: {}".format(algo.i... |
num=int(input())
#num1=int(input())
if(num<0):
print ("Negative")
elif(num==0):
print ("Zero")
else:
print ("Positive")
|
file = open("input.txt", "r")
groups = [string.split() for string in file.read().split(sep="\n\n")]
total = 0
total2 = 0
for group in groups:
# Create a dict of all questions and start the count at zero
question_dict = {}
for i in range(26):
question_dict[chr(ord('a')+i)] = 0
# For each perso... |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
# In this example, I walk through how to use sklearn to classify users into male or female
# based on their user description.
# First, we need to get some tweets in JSON format.
# Create a tweets.json file with something like:
# twitter-curl --query "tr... |
from __future__ import print_function
import tensorflow as tf
import numpy as np
# -------- Getting the dataset --------
# Functions for downloading and reading MNIST data
from tensorflow.examples.tutorials.mnist import input_data
# Load the training and test data into constants
mnist = input_data.read_data_sets("/tm... |
"""
Goal : Choose a random word from a given dictionary
"""
# Importing the required libraries
import random
import pandas as pd
def get_a_word():
"""
A function to read the words, also select a random word, return the board and the word.
return <[char, char...], string>
"""
wo... |
__author__ = 'coty'
from math import pow
def calc_amortization(rate, P, n):
"""
Method to calculate amortization given rate, principal, and terms remaining.
"""
# calc monthly interest rate
# doing this funky conversion stuff to drop off the remaining digits instead of round up.
i = float(str... |
import random
import logging
logger = logging.getLogger(__name__)
class Board:
def __init__(self, max_row=1, max_column=1):
assert max_row >= 1, f"Max row must be 1 or higher"
self.max_row = max_row
assert max_column >= 1, f"Max column must be 1 or higher"
self.max_column = max_col... |
person1 = {
'first_name': 'Kirk',
'last_name': 'Tolliver',
'age': '31',
'city': 'Chicago',
}
person2 = {
'first_name': 'Greg',
'last_name': 'Migos',
'age': '76',
'city': 'Mississippi',
}
person3 = {
'first_name': 'David',
'last_name': 'Banner',
'age': '45',
'city': 'Lous... |
import time
class Restaurant():
""" A simple Restaurant class"""
def __init__(self,r_name, r_cuisine):
""" Initialize restaurantaurant instances"""
self.r_name = r_name
self.r_cuisine = r_cuisine
self.number_served = 0
def describe_restaurant(self):
print(self.r_nam... |
pizzas = ["Cheese", "Suasage","Peperoni", "Olives", "Jalepeno"]
""" This is teext for git hub """
for pizza in pizzas:
print("I have "+ pizza +" Pizzas.")
print("I Love Pizza!")
freinds_pizza = pizzas[:]
freinds_pizza.append("Macaroni")
my_pizzas = [pie for pie in pizzas]
print("My favorite pizza is " + str(m... |
rental_car = input("Enter a car you would like to drive: ")
print("Let me see if we have a " + rental_car )
|
""" For loop inside of a list prints a list"""
cubes = [num**3 for num in range(1,11)]
print(cubes)
|
""" A class that displays characteristics of a Restaurant. """
import time
class Restaurant():
""" A simple Restaurant class"""
def __init__(self,name, cuisine):
""" Initialize restaurantaurant instances"""
self.name = name
self.cuisine = cuisine
self.number_served = 0
def d... |
#! /usr/bin/python
# Exercise No. 4
# File Name: extraCredit.py
# Programmer: Chris Adkins
# Date: Feb. 11, 2020
#
# Problem Statement: This program takes two numbers and divides them outputting using whole numbers and remainders.
#
# Overall Plan:
# 1. Define the numerator and denominator using user ... |
# Exercise No. 1
# File Name: hw7project1.py
# Programmer: Chris Adkins
# Date: Mar. 9, 2020
#
# Problem Statement: This program takes a number between 0 and 100 and returns the proper letter grade
# in accordance with the CS 138 grading scale.
#
# Overall Plan:
# 1. Create a functi... |
#! /usr/bin/python
# Exercise No. 1
# File Name: hw2project1.py
# Programmer: Chris Adkins
# Date: Feb. 4, 2020
#
# Problem Statement: Modify the convert.py program to have an introduction.
#
#
# Overall Plan:
# 1. add a print statement to the beginning of the program.
#
# Import the necessary python ... |
#!/usr/bin/env python
## Script to obfuscate given email address
##
import re
def obfuscate_id(email_id):
ret_list = []
components = re.split(r'(\.|\@)',email_id)
for ii in components:
if ii=='@':
ret_list.append("at")
elif ii==".":
ret_list.append("(dot)")
else:
ret_list.a... |
#!/usr/bin/python
import sys
## Kaprekar's number 6174
def high_to_low(n):
n_as_str=str(n)
slist = sorted(n_as_str)
slist.reverse()
sdigit_str = ''.join(slist)
return int(sdigit_str)
def low_to_high(n):
n_as_str=str(n)
slist = sorted(n_as_str)
sdigit_str = ''.join(slist)
return int(sdigit_str)
#... |
#!/usr/bin/env python3
nums1 = [1, 2, 3, 4, 4, 5] # expect true
nums2 = [7, 6, 3] # expect true
nums3 = [8, 4, 6] # expect false
# Returns True if list is sorted in ascending order
# False otherwise
def mono_incr(mylist):
sorted_ascending=True
for index in range(len(mylist)-1):
if mylist[index]>... |
#!/usr/bin/env python
# Script to create Hash of Hash
# after reading a file containing
# 3 fields per row
import sys
filename = sys.argv[1]
f = open (filename, "r")
# HashOfHash = { a => { c => d } }
HashOfHash={}
for line in f.readlines():
if len(line) <=0:
continue
col1,col2,col3=line.rstrip('\n').spli... |
#!/usr/bin/env python3
import typing
# 3.9 and above supports typing
def fact_with_type(n: int) -> int:
if n<=0:
return 1
else:
return n*fact_with_type(n-1)
# main
print(fact_with_type(10))
try:
print(fact_with_type("10.0"))
except TypeError as e:
print("MyError: This indicates that type is properl... |
from datetime import datetime
from implementations.code_df.utils import read_json_file
from implementations.code_df.issue_github import IssueGitHub
class IssuesNewGitHub(IssueGitHub):
"""
Class for Issues New
"""
def compute(self):
"""
Compute the number of new issues in the Perceval... |
from datetime import date
print('Hello Patient !')
print('* ' * 10)
name = input("Name of the patient : ")
birth_year = input("Birth year the patient : ")
is_admitted_before = input("Was the patient admitted before (Yes/No) : ")
print("-" * 20)
print("Name : " + name)
todays_date = date.today()
print(type(todays_date))... |
# students1 = []
# for _ in range(int(input("Number of students :"))):
# name = input("Name :")
# score = float(input("Score :"))
# students1.append([name, score])
# print(students1)
students = [['Atharva', 32.0], ['Uma', 32.8], ['Mangesh', 32.0], ['Tejashri', 32.8], ['Ameya', 32.0],
['Suman', 32.8... |
a = [11, 22, 33]
#浅拷贝
b = a
#深拷贝
import copy
c = copy.deepcopy(a)
print(id(a))
print(id(b))
print(id(c))
a = [11, 22, 33]
b = [44, 55, 66]
c = [a, b]
d = c
e = copy.deepcopy(c)
f = copy.copy(c)
a.append(00)
print(c[0])
print(e[0])
print(f[0])
|
import datetime
type_of_article = input("What type of article is this ( Electronic ): ")
author = input("What is the author's name: ")
title = input("What is the paper's title: ")
source = input("Where was the article sourced from ( Like New York Times, etc ): ")
datePublished = input("When was the paper published ( M... |
# name = input("Hello what is your name? ")
# age = int(input(f"Nice to meet you {name}. How old are you?"))
# List of films in each category
films_to_watch = {"under_12": ["All Dogs Go to Heaven", "Chicken Little", "The Mighty Ducks", "D2: The Mighty Ducks"],
"under_15": ["Forest Gump", "Black Panth... |
# isogram = input("Which word would you like to test for being an isogram? ").lower()
def iso_test(word):
isogram = word.replace(" ", "").replace("-", "")
if isogram and len(set(isogram)) == len(isogram) or len(word) == 0:
return True
else:
return False
def iso_test2(string):
for ite... |
#!/usr/bin/python
"""
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10001st prime number?
"""
import math, sys
def isPrime(number):
if number < 4:
return True
if number % 2 == 0 or number % 3 == 0:
return False
numMax = int(math.ceil(math.sqrt(n... |
#!/usr/bin/python
"""
Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the eve... |
from exercise_21 import Product
# Create an instance
pro1 = Product(101, "Coke", 25.00)
pro2 = Product(208, "Lays Chips", 105.00)
pro3 = Product(560, "Mott's Apple Juice", 200.00)
products = [pro1, pro2, pro3]
for product in products:
print("ID: " + str(product.id))
print("Description: " + product.descript... |
import random
class Flight: # flight class
def __init__(self, flight_name, flight_no): # constructor
self.flight_name = flight_name
self.flight_no = flight_no
def display(self): # display flight details
... |
import smtplib
import getpass
def connect_to_server():
"""
Connects to gmail server
Returns
-------
server : smtplib.SMTP_SSL
gmail email server
"""
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
return server
def get_credentials():
"""
Gets email... |
import time
def is_amstrong_number(number):
digits_of_number = [int(x) for x in str(number)]
total = 0
number_of_digits = len(digits_of_number)
i = 0
while ( i < number_of_digits ):
total = total + ( digits_of_number[i] ** number_of_digits )
i = i + 1
... |
class Solution:
def thirdMax(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
if len(nums) == 2:
return max(nums[0], nums[1])
first = nums[0]
second = third = float('-inf')
for num in nums:
if num > first:
... |
#виведіть на екран елементи лінійного масиву (заданий користувачем) у зворотньому порядку
#Курдупов Олексій 122-Г
import numpy as np#імпорт бібліотеки нампі
while True:
while True:
try:
a=int(input('Введіть кількість елементів: '))#вводимо кількість елементів
break
except ValueErro... |
"""
Problem statement:
It was one of the places, where people need to get their provisions only through fair price (“ration”) shops.
As the elder had domestic and official work to attend to, their wards were asked to buy the items from these shops.
Needless to say, there was a long queue of boys and girls. To ... |
"""
Common Elements in Three Array
"""
def commonele(A,B,C):
common = list(set(A) & set(B) & set(C))
return common
arr1 = [1,2,3,4,5]
arr2 = [2,3,4,6,9,8]
arr3 = [2,3,6]
print(commonele(arr1,arr2,arr3)) |
def sortt(a):
a.sort()
return a
numbers = [0,2,1,2,0]
# Sorting list of Integers in ascending
print(sortt(numbers))
|
"""
ar = [1,2,3]
max=3
min=1
"""
def maxmin(a):
return (max(a),min(a))
arr = [1000, 11, 445, 1, 330, 3000]
print(maxmin(arr)) |
#!/usr/bin/python
import math
for i in range(1, 15):
denorminator = math.factorial(3*i)
temp = math.factorial(i)
divisor = pow(temp, 3)
print i, denorminator/divisor
|
# create the initial variables below
age = 28
sex = 0
bmi = 26.2
num_of_children = 3
smoker = 0
# Add insurance estimate formula below
insurance_cost = 250 * age - 128 * sex + 370 * bmi + 425 * num_of_children + 24000 * smoker - 12500
print("This person's insurance cost is " + str(insurance_cost) + " dollars."... |
def get_sum_2020_2n(numberslist):
numberslist2020 = [2020 - x for x in numberslist]
for en, x in enumerate(numberslist):
if x in numberslist2020[en:]:
return x, 2020 - x
def get_sum_2020_3n(numberslist):
numberslist2020 = [2020 - x for x in numberslist]
for en, x in enumerate(num... |
##Check whether the input number is an odd number or not
##And then, if the input number is an odd number, print next 5 odd numbers
##else, print next 5 even numbers
run = True
print('Type "break" if you want to stop')
while(run):
userInput = input('Your number : ')
if(userInput == 'break'):
... |
import os
def SaveCSV(array_to_write, output_filename):
#initialize variables
i = 1
ensureDir(output_filename)
root_filename = stripCSV(output_filename)
# check filename doesn't exist
csv_filename = root_filename
while os.path.exists(csv_filename + '.csv'):
print csv_filename... |
#
# An exercise script on random number generation/manipulation.
# ref. http://effbot.org/librarybook/random.htm
#
import random
import sys
print '0.0<=float<1.0 10<=float<20 100<=int<= 1000 100<=even int.< 1000'
for i in range(5):
#print '| random float: 0.0 <= number < 1.0'
print '%15.13f' % random.rando... |
import numpy as np
import matplotlib.pyplot as plt
class Perceptron(object):
def __init__(self, no_of_inputs, name, threshold=100, learning_rate=0.01):
self.threshold = threshold
self.learning_rate = learning_rate
self.weights = np.zeros(no_of_inputs + 1)
self.name = name
def ... |
print("野兽先辈XX说自动论证机")
name = input("你想论证的人是?")
sex = input("他/他的性别是?(男性或者女性)")
true = input("他是在现实中存在的人吗?(是或不是):")
hurt = input("他是否被当成群友的乐子?(是或不是):")
win = input("他做过的好事:")
fail = input("他做过的坏事:")
want = input("他的梦想:")
print("迄今为止,野兽先辈的身份说法已经有1145141919810种,笔者今天经过考证发现了另一种可能!野兽先辈的本体乃是" + name +"!论证如下:")
if sex == "男性":... |
animals = ['dog','cat','pig']#animals列表中共有3中动物
for animal in animals:#将animals中三种动物储存在animal中
print(animal)#打印列表animals中的元素
print('i like animal like,'+animal.title()+',\n')
print('i am really like animal,i think ther are my friend'+'\n')
numbers = list(range(0,8))
print(numbers) |
"""
* About
*
* Author: seventeeen@GitHub <powdragon1@gmail.com>
* Date : 2017-02-22
* URL : https://www.acmicpc.net/problem/10820
*
"""
try:
while True:
a = raw_input()
length = len(a)
u = l = d = s = 0
for i in range(length):
if a[i].isupper():
... |
"""
* About
*
* Author: seventeeen@GitHub <powdragon1@gmail.com>
* Date : 2017-02-21
* URL : https://www.acmicpc.net/problem/5598
*
"""
s=raw_input()
x=''
for i in range(len(s)):
if ord(s[i])-ord('A')<3:
x+=chr(ord(s[i])+23)
else:
x+=chr(ord(s[i])-3)
print x
|
"""
* About
*
* Author: seventeeen@GitHub <powdragon1@gmail.com>
* Date : 2017-02-21
* URL : https://www.acmicpc.net/problem/5363
*
"""
n = input()
for i in range(n):
s = raw_input().split(' ')
s.append(s[0])
s.append(s[1])
s.pop(0)
s.pop(0)
result = ''
for j in range(len(s)):
... |
"""
* About
*
* Author: seventeeen@GitHub <powdragon1@gmail.com>
* Date : 2017-02-22
* URL : https://www.acmicpc.net/problem/11655
*
"""
s = raw_input()
c=''
for i in range(len(s)):
if s[i].isupper():
if ord(s[i])-ord('A')<13:
c += chr(ord(s[i])+13)
else:
c += chr(o... |
def partition(array, left, right):
pivot_value = array[left]
left_marker = left
right_marker = right
while left_marker < right_marker:
while left_marker <= right and array[left_marker] <= pivot_value:
left_marker += 1
while left <= right_marker and array[right_marker] > p... |
total = int(input())
for i in range(1,total+1):
n = int(input())
sum = 0
for c in range(1,n+1):
sum = sum + c**3
print(str(sum))
|
import random
random_num = random.random()*100
def grade(num):
if num <60:
print "Score:", num, "; Your grade is F"
elif num <= 69 and num >= 60:
print "Score:", num, "; Your grade is D"
elif num <= 79 and num >= 70:
print "Score:", num, "; Your grade is C"
elif num <= 89 and num >= 80:
print "Score:", num... |
class MathDojo(object):
def __init__(self):
self.result = 0
def add(self, *j):
for i in j:
if type(i) == int:
self.result += i
else:
for x in i:
self.result += x
return self
def subtract(self, *j):
for i in j:
if type(i) == int:
self.result -= i
else:
for x in i:
self.... |
def odd_even():
for x in range(1, 2001):
if x % 2 == 0:
print "Number is", x,"This is an even number."
else:
print "Number is", x,"This is an odd number."
odd_even()
def multiply(arr, num):
for x in range(0, len(arr)):
#print x
arr[x] *= num
return arr
print multiply([2,3,5,6], 5)
def layered_mult... |
bio = {"name": "Justin",
"age": 27,
"country of birth": "The United States",
"favorite language": "Python"}
#print bio["name"]
def info():
for key in bio:
#bio[key] ---> look at it as if the key to the
#dictionary unlocks the value, and that is what
#is displayed
print "My",key, "is", bio[key]
info() |
class Animal(object):
def __init__(self, name, health):
self.name = name
self.health = health
def walk(self):
self.health -= 1
return self
def run(self):
self.health -= 5
return self
def display_health(self):
print self.health
# # Animal1 = Animal("Elephant", 100)
# Animal1.walk().walk().walk()... |
'''
@Title: Testing triangle classification
@Author: PuzhuoLi CWID:10439435
@Date: 2019-01-26 13:24:16
'''
import unittest
import math
from HW01_pli import classify_triangle
class TestTriangle(unittest.TestCase):
'''
Test HW01 triangle classification
equilateral triangles have all ... |
from datetime import datetime, timedelta, date
def month_ago(dt):
"""
>>> month_ago(datetime(1969, 7, 21, 14, 56, 15))
datetime.datetime(1969, 6, 21, 4, 27, 9)
"""
return dt - timedelta(days=30.436875)
datetime.now() - timedelta(hours=3)
date(1961, 4, 12) - timedelta(days=3)
now = datetime.now(... |
class File:
def __init__(self, name, content=[]):
self.name = name
self.content = content
def append(self, line):
self.content.extend(line)
def write(self):
with open(self.name, 'w') as file:
file.write(self.content)
def __enter__(self):
pass
... |
import pygame
from pygame import *
import time
import random
pygame.init()
width=800
length=600
gamedisp=pygame.display.set_mode((width,length))
pygame.display.set_caption("wwwooww")
clock=pygame.time.Clock()
blue=(255,255,255)
black=(0,0,0)
green=(0,255,0)
myimg=pygame.image.load("car.png").convert_al... |
# Урок 7, задача №2
# Отсортируйте по возрастанию методом слияния одномерный вещественный массив,
# заданный случайными числами на промежутке [0; 50).
# Выведите на экран исходный и отсортированный массивы.
import random
SIZE = 10
MIN_ITEM = 0
MAX_ITEM = 49
array = [random.randint(MIN_ITEM, MAX_ITEM) for _ ... |
# Урок 2, задача №4
"""
Найти сумму n элементов следующего ряда чисел:
1, -0.5, 0.25, -0.125,…
Количество элементов (n) вводится с клавиатуры.
"""
# https://drive.google.com/file/d/1GT181Ddb1Aa7eHZa0Z7IvIQe6Mg5Nyww/view?usp=sharing
def rec(count, base_num):
if count <= 1:
return base_num
... |
# Урок 3, задача №2
"""
Во втором массиве сохранить индексы четных элементов первого массива.
Например, если дан массив со значениями 8, 3, 15, 6, 4, 2,
второй массив надо заполнить значениями 0, 3, 4, 5, (индексация начинается с нуля),
т.к. именно в этих позициях первого массива стоят четные числа.
"""
import random
... |
from rectangle import Rectangle, Square, Circle
rectangle_1 = Rectangle(5, 10, 50, 100)
square_1 = Square(10, 10, 30)
circle_1 = Circle(30, 50, 70)
print("Rectangle init: " + str(rectangle_1))
print("Square init: " + str(square_1))
print("Circle init: " + str(circle_1))
|
from utilities import *
# Advent of Code 2020
# Brendan Thompson
# Day 08
# Star 1
def run_script(path):
"""
Execute the program specified in the data: tracking the accumulator, and printing the accumulator before executing a line twice
"""
# Read Data
print("Reading file: ", path, "...")
data... |
# Advent of Code
# Brendan Thompson
# Day 03
# Star 2
# https://adventofcode.com/2020/day/3
print("Advent of Code Day 03")
def get_next_position(x, y, movement_x, movement_y, map):
# Get the next position given the current row and height
x = x + movement_x
y = y + movement_y
# Handle Wrap
ma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.