text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Gerar a informação de BUY, a compra realizada para o par SESSION, ITEM.
#INPUT
##SESSION, DAY, MONTH, YEAR, TIME, ITEM, CATEGORY
#14679, 03, 04, 2014, 04.73, 214645087, 0
#14672, 02, 04, 2014, 07.61, 214664919, 0
#14672, 02, 04, 2014, 07.61, 214826625, 0
#... |
files = ("HarkTheHerald.txt", "JoyToTheWorld.txt","AngelsWeHaveHeard.txt")
new_file = ""
def get_fixed_filename(files_new):
new_file = ""
for filename in files_new:
for i, letter in enumerate(filename):
new_file += letter
print(new_file)
try:
if let... |
import pymysql
from pymysql.cursors import DictCursor
connection = pymysql.connect(
host='localhost',
user='root',
password='123456',
db='sys',
charset='utf8mb4',
cursorclass=DictCursor)
try:
with connection.cursor() as cursor:
answer = input("Would you like to add new guest to DB?... |
# Convolutional Neural Network
# Part 1 - Building the CNN
# Importing the keras libraries and packages
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
#Initialising the CNN
classifier=Sequ... |
"""
https://adventofcode.com/2016/day/1
Note: Implemented for speed in terms of solving the solution, not for efficiency or scalability
"""
import unittest
def process_directions(start_position, directions, stop_on_same_location=False):
north = 0
east = 1
south = 2
west = 3
x_pos = start_po... |
"""
https://adventofcode.com/2020/day/6
Note: Implemented for speed in terms of solving the solution, not for efficiency or scalability
"""
import unittest
input_file = r'resources/day7_input.txt'
def part_1(data):
for line in data:
print(line)
return -1
def read_input_data(filename):
with o... |
# OSM Points and Streets
# Build from nodes and ways
# For each node, add it to node-ids with lat and lng
# For each way, add them to Streets
## If Street has a node with a previous street, build a connectsto relation between the two
# 0) Opening the file
import urllib, urllib2
osmfile = open('macon.osm', 'r')
allno... |
import numpy as np
import time
import random
"""
neuralnet.py
~~~~~~~~~~
The functions in this module will allow for the creation of a
feed-forward neural network with standard sigmoidal units.
The weights for each node will be optimized with a stochastic gradient descent
function (the derivatives will be calculated... |
class HTMLNode:
def __init__(self, tag="", attributes=(), content="", inline=False):
self.tag = tag
self.attributes = attributes
self.children = []
self.content = content
self.parent = None
self.inline = inline
def addChild(self, child):
self.childr... |
student = {'first_name':'robin','last_name': 'islam', 'gender': 'male', 'age': 22, 'martal status': 'single', 'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], 'country':'Bangladesh', 'city': 'dhaka', 'address': 'gulshan'}
key = student.keys()
print(key) |
from tkinter import *
from tkinter import messagebox
window = Tk()
#function conver Kg to G
def ConvertKgtoG():
tmp = float(txtIn.get())*1000;
messagebox.showinfo('Kilograms To Grams',str(tmp) + ' Grams')
#function conver Kg to Metric Tons
def ConvertKgtoMT():
... |
#!/usr/bin/python3
"""This module contain a function that add two integers
Args:
a (int): first parameter
b (int): second parameter
"""
def add_integer(a, b=98):
"""add_integer function that add two integers
Returns:
int: Addition between a + b."""
if type(a) is not int and type(a) is not... |
#!/usr/bin/python3
"""This module contains a function called write_file"""
def write_file(filename="", text=""):
"""write_file function that overwrite a file or create new file
Args:
filename (str, optional): file name. Defaults to "".
text (str, optional): string to write inside the file. De... |
#!/usr/bin/python3
"""This module contain a function that prints a square"""
def print_square(size):
"""print_square function prints a square
Args:
size (int): size of the square
"""
if type(size) != int or (type(size) != int and size < 0):
raise TypeError("size must be an integer")
... |
#!/usr/bin/python3
from sys import argv
len_args = len(argv) - 1
if __name__ == "__main__":
print("{:d} {}{}".format(len_args, "argument\
" if len_args == 1 else "arguments", ".\
" if len_args == 0 else ":"))
i = 1
while i <= len_args:
print("{:d}: {}".format(i, argv[i]))
i += 1
|
#!/usr/bin/python3
"""This module contains a class that defines a square.
In the Square class we initialize each object by the
__init__ method with a private instance variable called
__size that takes the size variable's value passed as
argument. Also checks if the size arg has a valid value.
area method returns the a... |
#!/usr/bin/python3
"""This module contain a function that divides all elements of a matrix"""
def matrix_divided(matrix, div):
"""matrix_divided function divides all elements of a matrix
Args:
matrix (list of lists): two dimension matrix
div (int, float): divisor
Returns:
list of lists: ... |
#!/usr/bin/python3
"""This module contain a class that inherits list class"""
class MyList(list):
"""Mylist class that inherits list class
Args:
list (class): list class
"""
def print_sorted(self):
"""print_sorted function that prints a list in sorted way"""
print(sorted(self)... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 12 12:55:08 2019
@author: jai
"""
x = 10
y = 3
print("10 divided by 3 is", x/y)
print("remainder after 10 divided by 3 is", x%y) |
#Justin Mitchell
#2/22/2021
#Problem 1 Area of a Circle
import math
def areaOfCircle(radius):
return math.pi * radius ** 2
r = float(input(" Please enter the radius of a circle: "))
area = areaOfCircle(r)
print(" Area Of a Circle = %.2f" %area)
#Program asks the user to enter the radius o... |
import cs50
from sys import argv, exit
if len(argv) != 2:
# if not correct display message for correct usage and exit program with code (1)
print("Usage: python roster.py house")
exit(1)
# call database as SQL function
db = cs50.SQL("sqlite:///students.db")
# SELECT from the table where house = command... |
from itertools import zip_longest
DAY = 'day'
HOUR = 'hour'
NAME = 'name'
class Formatter:
def __init__(self, indent=5 * ' '):
self.indent = indent
def append(self, text, tag=None):
raise NotImplementedError('Must override append() in derived class')
def println(self, *args):
se... |
# 1. 交換值
from xml.etree.ElementTree import Element
import sys
x, y = 1, 2
print(x, y)
x, y = y, x
print(x, y)
# 2. 字符串列表合併為一個字符串
sentence_list = ["my", "name", "is", "George"]
sentence_string = " ".join(sentence_list)
print(sentence_string)
# 3. 將字符串拆分為子字符串列表
sentence_string = "my name is George"
sentence_string.spl... |
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
xtrain, ytrain = mnist.train.next_batch(5000)
xtest, ytest = mnist.test.next_batch(200)
xtr = tf.placeholder("float", [None, 784])
xte = tf.placeholder(... |
#!/usr/bin/env python
import unittest
from acme import Product
from acme_report import inventory_report, ADJECTIVES, NOUNS
from random import randint
class AcmeProductTests(unittest.TestCase):
"""Making sure Acme products are the tops!"""
def test_default_product_price(self):
"""Test default product ... |
s=input()
buff=[]
for x in s:
if x == "0" or x == "1":
buff.append(x)
else:
if len(buff) > 0:
buff.pop()
print("".join(buff))
|
s=input()
vowel=["a","e","i","o","u"]
if s in vowel:
print("vowel")
else:
print("consonant")
|
A,a=input().split()
if A.lower()==a:
print("Yes")
else:
print("No")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
input = raw_input()
num_input = int(input)
if num_input < 1000:
input = '%03d' % num_input
output = "ABC"
else:
input ='%03d' % (num_input - 999)
output = "ABD"
print output
|
S = list(input().split())
d = set()
for x in S:
tmp = ""
for y in x.split("@")[1:]:
if y:
d.add(y)
d = list(d)
d.sort()
print(*d, sep="
")
|
import math
N = int(input())
n = math.sqrt(N)
if n == math.floor(n):
print(N)
else:
print(pow(math.floor(n), 2))
|
N=int(input())
k=0
while(2**k <= N):
k+=1
print(2**(k-1))
|
X = int(input())
y = X % 105
z = X // 105
if y >= max(0, 100 - 5*z) or y == 0:
print(1)
else:
print(0)
|
import collections
N=int(input())
table=collections.defaultdict(int)
for i in range(N):
table[input()]+=1
vote=0
ans=""
for x in table:
if vote < table[x]:
ans=x
vote=table[x]
print(ans)
|
c1=input()
c2=input()
for i in range(3):
if c1[i]==c2[-1-i]:
continue
else:
print("NO")
exit(0)
print("YES")
|
import collections
N = int(input())
table = collections.defaultdict(list)
for i in range(N):
table[int(input())].append(i)
table = list(table.keys())
table.sort()
print(table[-2])
|
N=int(input())
if N == 3 or N == 5 or N == 7:
print("YES")
else:
print("NO")
|
# To use this program, create a .txt file that contains your HTML source code and name it 'htmlfile.txt'
# Date Created: 10/18/2015
# Date Last Modified: 10/19/2015
import re
class Stack:
# List implementation of Stack
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def pu... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 17 15:58:04 2020
@author: Mack
"""
# Rocket.py
import math
import numpy as np
import matplotlib.pyplot as plt
import pprint
DT = 0.01 # set our delta t (s)
gravity = -9.81 # set grav... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 26 19:00:14 2020
@author: ntruo
"""
#%% Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#%% Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:,1:-1].values
y = dataset.iloc[:,-1].values... |
import math
import bisect
def SieveOfEratosthenes(n):
# Create a boolean array "prime[0..n]" and initialize
# all entries it as true. A value in prime[i] will
# finally be false if i is Not a prime, else true.
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
# If prime[p]... |
import math
def issquare(D):
return (math.floor(math.sqrt(D))**2 == D or math.ceil(math.sqrt(D))**2 == D )
def evaluate_continued_fraction(denom):
frac_num = 0
frac_denom = 1
for i in range(len(denom)-1, -1, -1):
frac_num += denom[i]*frac_denom
if(i != 0):
temp = frac_denom... |
def credit_range(credit): #def for credit range
check = False
for i in range (0,130,+20): #Range of Credits
if(credit==i):
check = True
break
return check
count=0
progress=0
trailing=0
retriever=0
excluded=0
Pass_credit=0
print("This Programme Allow Staff To Predict s... |
import Variables
import Functions
import pygame
import Snake
import Levels
def pause(snake):
"""
Displays Pause Screen.
Args:
snake (obj): Object of class Snake.
"""
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
Functions.... |
word = input("Enter word :")
word=word.split(',')
word=sorted(word)
ans=''
for x in word:
if x != word[len(word)-1]:
ans=ans+x+','
else:
ans=ans+x
print(ans)
|
a=input()
check=['YES','yes','Yes']
if a in check:
print('Yes')
else:
print('No') |
string=input()
alpha=0
numeric=0
for s in string:
if ord(s) in range(65,91) or ord(s) in range(97,123):
alpha+=1
if ord(s) in range(48,58):
numeric+=1
print('LETTERS ',alpha)
print('DIGITS ',numeric)
|
#Function Exercises
#make sure you add code to each to check for good input before using the input
#also add comments with each line explaining what its doing
#Exercise 1
x = input('Input: ')
def is_two(x):
if x == '2' or x == 2:
return True
else:
return False
#Exercise 2
vowels = {"a", "e", "... |
def hex_to_dec(hexa):
hexa_table = ['0','1', '2','3','4','5','6','7','8','9','10','a','b','c','d','e']
for num in range(len(hexa_table)):
if hexa == hexa_table[num]:
return num |
from csv import reader
from csv import DictReader
warning_data = 'p_483_2020.csv'
def main():
print('*** Read csv file line by line using csv module reader object ***')
print('*** Iterate over each row of a csv file as list using reader object ***')
# open file in read mode
with open(warning_data, 'r'... |
import wikipedia
from wikipedia.wikipedia import search
search = input("Enter a search topic:")
result = wikipedia.summary({search}, sentences = 2)
print(result) |
#Feature 1
#create a csv file of different customer orders where each row contains a
# customer order along with customer name address and phone number
#after you have built that out you will create a function to change the name, and for extra credit (because some customers change the phone numbers) add in a way... |
bin_str = input('Enter in a binary: ')
def bin_to_dec(bin_str):
answer = int(bin_str, 2)
print('Binary value has the decimal value of:', answer)
bin_to_dec(bin_str) |
km = float(input('Qual a distância da sua viagem em Km? '))
if km <= 200:
pr1 = km*0.50
print('Você vai pagar na sua viagem: {:.2f}'.format(pr1))
else:
pr2 = km*0.45
print('Você irá gasta na sua viagem: {:.2f}'.format(pr2))
print('Boa Viagem!') |
d1 = int(input('Quanto de dinheiro você tem na carteira?'))
d2 = d1/3.27
print('Você tem {} na carteira e pode comprar {:.2f} de dólares'.format(d1, d2))
|
n1 = int(input('Digite qualquer número inteiro:'))
if n1 % 2 == 0:
print('Esse numero é par!')
else:
print('Esse numero é ímpar!') |
s1 = int(input('Qual o salario atual: '))
s2 = s1*(15/100)
s3 = s1+s2
print(' O salário atual é: {}\n Com aumento de 15% passa a ser de {:.0f}'.format(s1, s3))
|
#while loop
i = 1
while i<=7:
print(i)
i = i + 1
print("Finished!")
print()
#break
i = 0
while 1==1: #infinite loop
print(i)
i = i + 1
if i >= 5:
print("Breaking")
break
print("Finished")
print()
#Continue
i = 0
while True:
i = i +1
if i == 2:
print("Skippi... |
#check the 3 sections one by one using the comments. we cant compile the 3 types at a time bcs after giving an exception the program exits.
"""
An assertion is a sanity-check that you can turn on or turn off when you have finished testing the program.
An expression is tested, and if the result comes up false, an e... |
#simple operations
print(2+2)
print(2 + 5 * 10)
print(5 * 10 + 2)
print(2*(3+4))
print(10/2)
print(10//2)
print(-7)
print(-5+5)
print(-7-7)
print((-7+2)*(-4))
# print(11/0) -> it produces ZeroByDivisionError
print(6*7.0)
#exponention
print(2**5)
print(2**1/2)
print(3**(3**3))
print(3**3**3)... |
import os
def percent(num1, num2):
return (num1 / num2)
# Take input from the user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
with open(os.path.expanduser("~/Ansible_numa/results/percentage.txt"), 'w') as f:
print("The packetdrop percentage is", percent(num1, num2... |
class Dog:
def __del__(self):
print('-----英雄over----')
dog1 = Dog()
dog2 = dog1
del dog1 #不会调用__del__方法,因为这个对象还有其他的变量指向它,即引用计算不是0
print('============')
del dog2 #此时会调用__del__方法,以为没有变量指向它
print('============')
#如果在程序结束时,有些对象还存在,那么python解释器会自动调用他们的__del__方法来完成清理工作
|
class Dog:
def __init__(self, new_name):
self.name = new_name
self.__age = 0
#定义了一个私有的属性,属性的名字是__age
#同过内部定义的方法设置私有属性
def set_age(self, new_age):
if new_age > 0 and new_age <= 100:
self.__age = new_age
else:
self.__age = 0
#通过内部定义的方法调用返回... |
from prac_08.unreliable_car import UnreliableCar
def main():
"""Test some unreliable cars"""
# create cars with different reliabilities
car_one = UnreliableCar("Car 1", 100, 90)
car_two = UnreliableCar("Car 2", 100, 10)
# attempt to drive the cars 10 times
# output what distance they drove
... |
def intersection(arrays):
"""
YOUR CODE HERE
"""
result = []
store = {}
# store each number from each array as {number: count} in a dictionary
for arr in arrays:
for num in arr:
if num not in store:
store[num] = 1
else:
store[... |
import random
lst = []
n = int(input("Довжина списку: "))
for i in range(n):
lst.append(random.randint(0, 10))
print(lst)
def func(lst):
for i in range(len(lst)):
if lst[i]>lst[i+1]:
return True
else:
return False
print(func(lst))
|
import random
# a = []
# b=[]
# for i in range(1,10):
# a.append(random.randint(0, 100))
# for i in range(1,10):
# b.append(random.randint(0,100))
# print(a)
# a.sort()
# print(b)
# b.sort()
# print(a)
# print(b)
lst_1 = []
lst_2 = []
n = int(input("Довжина першого списку: "))
m = int(input("Довжина другого спи... |
print(12 > 44) # False, т.к 12 меньше 44
print(12 == 44) # False, т.к 12 не равно 44
print(12 < 44) # True, т.к 12 меньше 44
print("*" * 50)
print(bool("Hi!"))
print(bool(1))
# Функция bool( ) возвращает True в случае если аргумент не равен нулю или если аргумент не пустая последовательность
# и если аргумент содер... |
import random
n = int(input("Введіть кількість чисел: "))
i = 1
avg = 0
while n >= i:
num = random.randrange(1, n + 1)
print(num)
avg = avg + num
i += 1
print(f'Середнє арифметичне чисел = {avg / n}')
def func(n):
i = 1
fct = 1
while n >= i:
fct = fct * i
i += 1
return... |
# Конкатенація списків
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
c = a + b
print(c)
# Конкатенація через extend
a.extend(b)
print(a)
# Функція len()
d = [1, 2, 3, 4]
e = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
print(len(d))
print(len(e))
# Конструкція if variable in collection
f = [3, 1, 9, 0]
print(f)
# 0 есть в списке f
if 0 in f:... |
n = int(input())
for i in range(n):
s = input()
k = 0
odd = ""
even = ""
for j in s:
if k % 2 is 0:
odd += j
else:
even += j
k += 1
print("%s %s" % (odd, even))
|
# f = open("../data/readme.txt",'r')
# string = f.read()
# print(string)
# strline = f.readline()
# print(strline)
# f.close()
# f=open('../data/readme.txt','r')
# strline = f.readline()
# print(strline)
# f.close()
# f = open('../data/readme.txt','w')
# f.write('hello world \nhello')
# f.close()
'''
方法的重写
'''
# cla... |
import pandas as pd
import requests
import json
# !Elements of the Get Request
api_url = "https://api.data.gov/sam/v3/registrations"
api_key = 'VpTi8pF59uRnH9TY5djWg8YUWVNgeOut39RiEL1G'
status = 'registrationStatus:A'
zipcode = 'samAddress.zip:22201'
# ? Instead of using params, you can also build the ful... |
import math
class Point:
__x: float
__y: float
def __init__(self, x: float, y: float):
self.set_x(x)
self.set_y(y)
def set_x(self, x):
if not isinstance(x, float):
raise Exception
self.__x = x
def get_x(self):
return self.__x
def set_y(se... |
class Book:
__title: str
__author: str
__price: float
__chapters: list
def __init__(self, title, author, price, chapters):
self.__title = title
self.__author = author
self.__price = float(price)
self.__chapters = chapters
def get_title(self):
return self... |
def print_head(num):
for row in range(1, num + 1):
for col in range(1, row + 1):
print(f"{col} ", end='')
print()
def print_foot(num):
for row in range(num, 0, -1):
for col in range(1, row):
print(f"{col} ", end='')
print()
def print_triangle(num):
... |
numbers_list = list(map(int, input().split()))
numbers_list.sort(reverse=True)
square_numbers = []
for num in numbers_list:
if num > 0 and num**0.5 == int(num**0.5):
square_numbers.append(num)
print(" ".join(map(str, square_numbers))) |
dict = {}
while True:
asdf = input()
if asdf == 'Over':
break
(key, val) = asdf.split(' : ')
if val.isdigit():
dict[key] = str(val).strip()
else:
dict[val] = str(key).strip()
for key in sorted(dict):
print(f"{key} -> {dict[key]}")
|
string = input()
string_list = [x for x in string]
counts = {}
for letter in string_list:
cnt = string_list.count(letter)
counts[letter] = cnt
for key, val in counts.items():
print(f"{key} -> {val}")
|
list_strings = input().split()
list_strings = [str.lower() for str in list_strings]
counts = {}
for string in list_strings:
cnt = list_strings.count(string)
counts[string] = cnt
print(", ".join([key for key, val in counts.items() if val%2 != 0])) |
#!/usr/bin/env python
""" Takes in a base test file as the first argument using the -f flag
Parses through the base tests, and replaces values preceding with <
and proceeded with > with all possible named values of that kind.
The types must be defined before they can be replaced
i.e. running test_g... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 21 21:07:02 2021
@author: slb
"""
#The next two lines clears the workspace
from IPython import get_ipython
get_ipython().magic('reset -sf')
import os
file_path = os.path.join(os.path.curdir, "Dec6.txt")
with open(file_path) as f:
data = f.readlines(... |
# Author: Shao Zhang and Phil Saltzman
# Last Updated: 4/18/2005
#
# textureMovie.py shows how to set up a texture movie effect. This tutorial
# shows how to use that effect in a different context. Instead of setting the
# texture based on time, this tutorial has an elevator that sets a texture on
# its floor based on ... |
# Author: Shao Zhang and Phil Saltzman
# Last Updated: 4/18/2005
#
# This tutorial will cover fog and how it can be used to make a finite length
# tunnel seem endless by hiding its endpoint in darkness. Fog in panda works by
# coloring objects based on their distance from the camera. Fog is not a 3D
# volume object lik... |
empty = {} #Creates a dictionary of an empty key-value
my_dict = {"book":1, "Boys":3, "Girls":4} #Creates a my_dict dictionary of 3 Key_values
winning_lottery_numbers = dict([("class", True),("School", False)]) #Creates a dictionary from a tupule using the dict function |
class SymbolTable:
def __init__(self):
self.labelTable = {}
def addEntry(self, symbol, address):
self.labelTable[symbol] = address
def contains(self, symbol):
return True if symbol in self.labelTable else False
def getAddress(self, symbol):
return self.labelTable[symbo... |
"""
Your goal is to define a `Queue` class that uses two stacks. Your `Queue` class
should have an `enqueue()` method and a `dequeue()` method that ensures a
"first in first out" (FIFO) order.
As you write your methods, you should optimize for time on the `enqueue()` and
`dequeue()` method calls.
The Stack class that y... |
#4. Faça um programa que peça dois números, base e expoente, calcule
# e mostre o primeiro número elevado ao segundo número.
# Não utilize a função de potência da linguagem.
n1 = int(input("Informe um número para a base: "))
n2 = int(input("Informe o segundo número para o expoente: "))
bas = 1
for x in range(n2):
... |
#7. Faça um Programa que leia um número e exiba o dia correspondente da semana. (1-Domingo, 2- Segunda, etc.),
# se digitar outro valor deve aparecer valor inválido
n1 = int(input('Escreva um numero: '))
semana = ['sla', 'Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado']
if n1 <= 7 and n1 > 0:
... |
s1 = input()
s2 = input()
ctr,s=len(s1),''
vowels=['a','e','i','o','u','A','E','I','O','U']
while ctr>=0:
if s1[ctr] in vowels and s2[ctr] in vowels or s1[ctr] not in vowels and s2[ctr] not in vowels:
s+=s1[ctr]+s2[ctr]
s1,s2=s2,s1
else:
s+=s1[ctr]
ctr-=1
print(s) |
# mcountInversions.py
# input: an array of integers
# output: number of inversions that were in the array
#
# inversions count how many moves are needed to move out-of-place elements into an ordered list
# for example, in the list [3, 2, 1], 3 is two places out of place so that's two inversions; once 3 is in place, 1 i... |
"""Calendar class to wrap list of Appointments for Paxos Log Entries."""
from Appointment import Appointment
import datetime
class Calendar(object):
"""
Calendar object to function as container of Appointment objects, which
enforces logical rules of a calendar.
appointments: unordered ... |
'''
Summary: RSA Key Generation Principle
Author: bruno.on.the.road@gmail.com
Version: 0.2
Date: 18 Sep 2018
Platform: Ubuntu Server 18.04 LTS
python version: 3.6
RSA Key Generation Principle
----------------------------
1. Generate two large rand... |
#!/usr/bin/env python3
from collections import namedtuple
import aoc
DistLoc = namedtuple('DistLoc', ['distance', 'location'])
Slope = namedtuple('DistLoc', ['relation', 'slope'])
def parse_input(input_list):
"""
Parse input to a set of coordinate locations. Only locations with an asteroid will be put in
... |
#len() - dlugosc - length
#.append - dodac
#.extend - rozszerzyc
#.inset(index, co) - wstawic
#.index - indeks danego elementu
#sort(reverse=False) - sortuj rosnaco
#max()
#min()
#.count - ile razy cos wystapi
#.pop - usun ostatni element
#.remove - usun pierwsze wystapienie
#.clear - wyczysc liste
#.reverse - zamien... |
import sys
# wyrazenie lisowne
evenNumbers = [element
for element in range(400)
if (element % 2 == 0)
]
# wyrazenie generujace - wypisujemy dane i o nich zapominamy
evenNumbersGenerator = (element
for element in range(400)
... |
import math
print("1: Oblicz Pole prostokąta")
print("2: Oblicz pole kwadratu")
print("3: Oblicz pole trojkata")
print("4: Oblicz pole trapezu")
print("5: Oblicz pole koła")
wybor = input("Pole jakiej figury chcesz policzyc? ")
def pole_prostokata(a, b):
return a * b
def pole_kwadratu(a):
return a * a
de... |
import random
cardList = ["9", "9", "9", "9",
"10", "10", "10", "10",
"Jack", "Jack", "Jack", "Jack",
"Queen", "Queen", "Queen", "Queen",
"King", "King", "King", "King",
"Ace", "Ace", "Ace", "Ace",
"Joker", "Joker"]
random.shuffle(cardList)
for... |
"""
OOP - Object Oriented Programming
Programowanie zorientowane wokół obiektów
OBIEKT
OBIEKTY - to pojemniki do przechowywania zmiennych i funkcji tematycznie ze
sobą powiązanych do dalszego łatwiejszego ponownego użycia
Klasy - foremki (szablony) do tworzenia egzemplarzy obiektów
Atrybut - cecha opi... |
#petla
"""
suma = 0
x = int(input("Podaj kolejna liczbe")
suma += x
x = int(input("Podaj kolejna liczbe")
suma += x
x = int(input("Podaj kolejna liczbe")
suma += x
"""
#suma = 0
#x = int(input("Podaj kolejna liczbe")
"""
while - podczas gdy
"""
liczba = 100
while liczba >=0:
print (liczba)
liczba ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.