text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
r"""vernalequinox -- DESCRIPTION
"""
from abc import ABCMeta as _ABCMeta, abstractmethod as _abstractmethod
from datetime import date
__all__ = ['CalcVernalEquinox']
class Longitude(object):
r"""SUMMARY
"""
__metaclass__ = _ABCMeta
_month = 3
@_abs... |
hrs = float(input("Enter Hours:"))
rate = float(input("Enter Rate:"))
if hrs > 40:
result = hrs * rate
a = (hrs - 40) * (rate * 0.5)
result = result + a
else:
result = hrs * rate
print(result) |
#现在有多个字典或者映射,你想将它们从逻辑上合并为一个单一的映射后执行某些操作, 比如查找值或者检查某些键是否存在。
from collections import ChainMap
a = {'x': 1, 'z': 3 }
b = {'y': 2, 'z': 4 }
c = ChainMap(b,a)
print(c['x']) # Outputs 1 (from a)
print(c['y']) # Outputs 2 (from b)
print(c['z']) # Outputs 3 (from a)
#一个 ChainMap 接受多个字典并将它们在逻辑上变为一个字典。 然后,这些字典并不是真的合并在一起了,
#对于... |
#first create class
#self represet object when we create object
class Person:
def __init__(self,first_name,last_name,age):
# instance variable initilise
print("init method // constructor get called")
self.first_name = first_name
self.last_name = last_name
self.age = ... |
def even_odd(y):
if (y%2==0):
print("the number is even")
else:
print("the number is odd") |
#
# @lc app=leetcode id=145 lang=python3
#
# [145] Binary Tree Postorder Traversal
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def ... |
#
# @lc app=leetcode id=5 lang=python3
#
# [5] Longest Palindromic Substring
#
# @lc code=start
class Solution:
def longestPalindrome(self, s: str) -> str:
if not s:
return ""
n = len(s)
is_palindrome = [[False]*n for _ in range(n)]
for i in range(n):
is_pa... |
#
# @lc app=leetcode id=461 lang=python3
#
# [461] Hamming Distance
#
# @lc code=start
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
distance = 0
while(x !=0 or y!=0):
if(x%2 != y%2):
distance += 1
x = x //2
y = y //2
... |
#
# @lc app=leetcode id=530 lang=python3
#
# [530] Minimum Absolute Difference in BST
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
nu... |
#
# @lc app=leetcode id=240 lang=python3
#
# [240] Search a 2D Matrix II
#
# @lc code=start
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
if not matrix or not matrix[0]:
return False
rows = len(matrix)
cols = len(matrix[0])
row, co... |
def bubblesort(items):
lst = list(items)
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
if lst[j] < lst[i]:
lst[j], lst[i] = lst[i], lst[j]
return lst
|
#hangman using turtle
import turtle
import random
def draw(x):
if x==1: #h
t.circle(60)
elif x==2: #a
t.right(90)
t.right(30)
t.forward(100)
t.backward(100)
elif x==3: #n
t.left(60)
t.forward(100)
t.backward(100)
t.right(... |
def main():
print('Cálculo do fatorial de um número\n')
n = int(input('Digite um número inteiro não-negativo: '))
if n < 0:
print('Impossível calcular números negativos')
i = 1
n_fat = 1
while i <= n:
n_fat = n_fat * i
i = i + 1
print("%d! = %d" % (n, n_fat))
ma... |
import numpy as np
def game_core(number):
"""Guess a number with binary search
Keyword arguments:
number -- number to guess
"""
count = 0
start = 0
end = 101
predict = end // 2
while number != predict:
count += 1
if number > predict:
start = predi... |
import numpy as np #importamos numpy
import random #libreria para elegir al ganador
class Arreglos: #creamos una clase
array1 = []
array2 = []
diagonal = []
invetido = []
def _init_(self): #agregamos el constructor
pass
def crear_arreglos(self): #creamos un error
try: #intente ... |
"""
Elabora un codigo donde dada una palbra la
invierta (usa la estructura de datos pila)
"""
def stringToList(string):
ls=[]#declaracion lista
ls[:0]=string #pasar de str a lista
return ls#retornar la variable ls
def listToString(string):
str1 = "" #declaracion de string
for... |
# -*- coding:utf-8 -*-
# !/usr/bin/env pyhon3
#import matplotlib
import matplotlib.pyplot as plt
#matplotlib.use("Agg")
input_value = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]
plt.plot(input_value, squares, linewidth=5)
#设置图标标题,并给坐标轴加上标签
plt.title("Square Number", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.... |
def magic_tuples(total_sum, max_number):
return ((i, j) for i in range(1, max_number)
for j in range(1, max_number) if (i+j) == total_sum)
if __name__ == "__main__":
for t in magic_tuples(10, 10):
print(t)
|
class Foo(object):
_instances = []
def __new__(cls, x):
if x in cls._instances:
pass
else:
cls._instances.append(x)
return super(Foo, cls).__new__(cls)
def __init__(self, x):
self.x = x
class Uniquish():
_instances = []
def __new__(c... |
t = int(input())
for qwerty in range(t):
#n,q=input().split()
#n,q=int(n),int(q)
n=int(input())
#arr=list(map(int,input().split()))
firstName=[]
lastName=[]
for i in range(n):
x,y=input().split()
firstName.append(x)
lastName.append(y)
for i in range(n)... |
#!/usr/bin/env python
from collections import Counter, defaultdict
import sys
try:
columns = int(sys.argv[1])
except IndexError:
columns = 3
words = ['about', 'after', 'again', 'below', 'could', 'every', 'first', 'found', 'great', 'house', 'large', 'learn', 'never', 'other', 'place', 'plant', 'point', 'right'... |
from cola import Cola
from random import randint
# cola_datos = Cola()
# cola_aux = Cola()
# for i in range (0,10):
# num = randint(0,100)
# cola_datos.arribo(num)
# print(num)
# print()
# cantidad_elemento = 0
# while(cantidad_elemento < cola_datos.tamanio()):
# dato = cola_datos.mover_final()... |
#Password Checker
print("Welcome to PGO Security Systems")
print("*******************************")
attempts = 0
while attempts != 3:
password = input("Enter your password: ")
attempts = attempts + 1
if password == "abcd1234":
print("Access Granted")
attempts = 3
else:
... |
#!/usr/bin/python
"""TODO(prasana): DO NOT SUBMIT without one-line documentation for main.
A simple main function
TODO(prasana): DO NOT SUBMIT without a detailed description of main.
"""
import sys # sys.argv
import argparse ## for argument parsing
def print_str(s):
print (str(s))
def fact(n, verbose):
if n <= 1:
... |
# Zad. 1 Program do obliczania podatku.
"""Prosta aplikacja do liczenia należnego podatku z funkcją sprawdzania
poprawności wprowadzonych danych"""
def tax():
prompt = """Prosta aplikacja do liczenia należnego podatku z funkcją sprawdzania
poprawności wprowadzonych danych"""
pr1 = 3091
pr2 = 85528
s... |
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def show(self):
print(f'hi my name is {self.name} and my age is {self.age}')
d = Dog('fred', 15)
d1 = Dog('bob', 10)
d2 = Dog('blah', 3)
d.show()
d1.show()
d2.show()
|
def find_missing_element(l1, l2):
num = 0
for item in l1 + l2:
num ^= item
return num
print(find_missing_element([1,2,3,4,5], [1,3,4,5])) |
def is_anagram(s1, s2):
counts = {}
for letter in s1:
num = counts.get(letter, 0) + 1
counts[letter] = num
for letter in s2:
num = counts.get(letter, 0) - 1
counts[letter] = num
for letter in counts:
if counts[letter] != 0:
return False
return Tr... |
class Queue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def offer(self, item):
self.stack1.append(item)
def poll(self):
if not self.stack2: # nothing in the polling stack
while self.stack1: # add everything from the first stack
self... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 5 01:16:08 2021
@author: Astitva
"""
import turtle
win = turtle.Screen()
win.title("Pong")
win.bgcolor("black")
win.setup(width = 800, height = 600)
win.tracer(0)
#Paddle A
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.shapesize(s... |
inp = input()
flag = False
result = ""
tmp = ""
tmp2 = ""
for i in inp:
if not flag:
if i == "<":
flag = True
result += tmp[::-1]
tmp = "<"
elif i == " ":
if tmp:
result += tmp[::-1] + " "
tmp = ""
... |
# expression = input()
# neg = False
# tmp = ""
# answer = 0
# for ex in expression:
# if ex == "-":
# if "+" in tmp:
# if neg:
# answer -= sum(list(map(int, tmp.split("+"))))
# else:
# answer += sum(list(map(int, tmp.split("+"))))
# else:
# ... |
import math
M,N = map(int, (input().split()))
prime = [True for _ in range(N+1)]
prime[1] = False
for i in range(2, int(math.sqrt(N+1)+1)):
if prime[i]:
for j in range(i+i, N+1, i): # step i 를 이용해서 배수 제거 ☆
prime[j] = False
for i in range(M, N+1):
if prime[i]:
print(i)
|
n = int(input('Diga qual e o seu numero?'))
a = n - 1
s = n + 1
print('O antecessor do seu numero e:{}\ne o seu numero foi:{}\ne o seu sucessor e :{}'.format(a, n, s))
|
#m = float(input('digite o seu valor em metros: '))
#c = m * 100
#mm = m * 1000
#print('O seu valor em metros digitado foi de: {} e o seu valor convertidor em centimentros e:{}'.format(m,c))
#print('O seu valor convertidor em milimitros e:{}'.format(mm))
met = float(input('Uma distancia em metro: '))
km = met / 1000
h... |
s = 0
cont = 0
for c in range(1, 7):
n = int(input('Digite o {}º valor:'.format(c)))
if n % 2 == 0:
s += n
cont += 1
print('Você Informou {} numeros e a soma dos Pares foi {}'.format(cont, s))
s = 0
cont = 0
for c in range(1, 7):
n = int(input('Digite o {}º valor:'.format(c)))
if n % 2 ... |
print('-' * 15)
print('LOJA DO PAULO')
print('-' * 15)
total = totmil = menor = cont = 0
barato = ''
while True:
prod = str(input('Nome do Produto: '))
prec = float(input('Preço: R$ '))
cont += 1
total += prec
if prec > 1000:
totmil += 1
if cont == 1 or prec < menor:
menor = prec... |
'''
一个变量等于2000如果他大于1000会打印I'm rich!!不然就会打印I'm not rich!!But I might be later...
'''
money = 2000
if money > 1000:
print("I'm rich!!")
else:
print("I'm not rich!!")
print("But I might be later...") |
from tkinter import *
import random
tk =Tk()
canvas = Canvas(tk,width=400,height=400)
canvas.pack()
for m in range(0,101):
g = ['red', 'pink', 'green','gray']
h = random.randint(0,2)
a = random.randint(0, 400)
b = random.randint(0, 400)
c = random.randint(0, 400)
d = random.randint(0, 400)
e... |
'''
创造一个变量他等于5如果这个变量小于10会打印我打得过那些忍者,小于30会打印有点难,不过我能应付如果小于50会打印太多了
'''
ninjas = 5
if ninjas < 10:
print('我打得过那些忍者')
elif ninjas < 30:
print('有点难,不过我能应付')
elif ninjas < 50:
print('太多了')
|
import cv2
import imutils
# construct a range of colors of our ball,
# this sets a minimum and maximum range in HSV space and makes it white
# and makes everything else white. This mask is much easier to identify
# features in the image
greenLower = (73, 91, 52) # (h, s, v)
greenUpper = (82, 218, 255)
# No... |
numbers = [1, 2, 3]
print(numbers) # This will print as [1,2,3]
# What if you want to print individual numbers without square brackets, unpacking operator is used
print(*numbers) # unpacking operator
values = [*range(5), *"HELLO"]
print(*values) # unpacking operator
# We can combine two lists with unpacking oper... |
from sys import getsizeof
# When comprehension is used with tuple, generator object is created and we have to iterate over it
# Generator : it doesn't loads all the values in memory
values = (x*2 for x in range(100000))
print("gen :", getsizeof(values))
values = [x*2 for x in range(100000)] # It loads all the ... |
print ("Hores : ")
horas= int( input())
print ("Minuts : ")
minutos= int( input())
print ("Segons : ")
segundos= int( input())
hora_segundo=horas*3600
minutos_segundo=minutos*60
suma=hora_segundo+minutos_segundo+segundos
print(suma) |
import re
from typing import List, Optional
from word2number import w2n
from ._custom_types import *
from ._languages import Languages, Language
class WordsNumbersConverterException(Exception):
"""Exception thrown when the text representation of the number cannot be converted."""
pass
class WordsNumbersCo... |
#!/usr/bin/env python
import random
def roll(num = 1):
return [random.choice([u'\u2680', u'\u2681', u'\u2682', u'\u2683', u'\u2684', u'\u2685']) for x in range(num)]
if __name__ == '__main__':
import argparse
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('-n', default=1, type=int, help='numb... |
#########################################################################
# Date: 2018/10/02
# file name: 3rd_assignment_main.py
# Purpose: this code has been generated for the 4 wheel drive body
# moving object to perform the project with line detector
# this code is used for the student only
#########################... |
'''
Conceptualize a sorted half and an unsorted half
Initially the sorted half consists of just the first element
Iterate along the rest of the array
Place it in its appropriate spot in the sorted half
the sorted half grows until it encompasses the whole array
'''
class Book:
def __init__(self, title, author, genr... |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 28 12:10:12 2021
@author: Wilms
"""
import itertools
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pygmo as pg
import utils
matplotlib.rcParams['text.usetex'] = True
# %% Accuracy function
def acc(population, x0, f0, tar... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
"Vecteur des temperature (step1) to maillage"
def VectorToMatrix(vector,Nr,Nz):
a=vector.copy()
newMatrix=np.zeros((Nz,Nr))
for i in range(0,Nr):
for j in range(0,Nz):
pl=i+j*Nr
newMatrix[j,i]=a[pl]... |
# Necessary libraries
import random
import random
from statistics import median
# Common functions
#import numpy as np
#import pandas as pd
#import seaborn as sns
#import matplotlib.pyplot as plt
#from scipy import stats
# Class Population
class Population(object):
def __init__(self, dimensions,activism):
... |
"""
A Python script that will calculate the value of Pi to a set number of decimal places.
"""
from decimal import Decimal, getcontext
import math as m
import time as t
import colorama
from colorama import Fore as f
colorama.init()
numberofdigits = int(input("Please enter the number of decimal places to calculate P... |
"""
Unit tests provide a way of testing individual components of your program.
This will help you with debugging and making sure you don't break your code!
Here, we provide some unit tests and a skeleton for a few others.
Note that you do not have to follow these exactly, they are designed to help you.
What other ... |
#Vérifier si un nombre est premier
a,compt=1,0
print('Entrez un nombre : ')
numb=int(input)
while a<=numb:
if numb%a==0:
compt+=1
a+=1
else:
a+=1
if compt==2:
print(numb,'est un nombre premier')
else:
print(numb,'n\'est pas un nombre premier') |
import itertools
# declaram un dictionar ca sa tinem scorul
scoreboard = {1: 0, 2: 0}
# declaram o variabila pentru numarul de jocuri
game_count = int(input("How many times do you want to play? Enter a number: "))
# declaram o variabila pentru numarul de miscari
game_moves = 0
def win(current_game):
d... |
def number_of_ways_to_form_coin(coin):
"""
"""
count = 0
for two_pound in xrange(0, 2):
if (two_pound * 200) > coin:
break
for one_pound in xrange(0, 3):
if (one_pound * 100) > coin:
break
for fifty_p in xrange(0, 5):
if... |
POWER = 5
MIN = 0
MAX = 999999
def power_of(n, exp=POWER):
r = 1
i = 0
while i < exp:
r *= n
i += 1
return r
def get_sum_of_powers(n):
digits = []
while (n > 0):
digits.append(n % 10)
n /= 10
digits = [power_of(i) for i in digits]
r = 0
for i in digi... |
def isNumeratorLonger(num, den):
"""
"""
return len(str(num)) > len(str(den))
def calc():
"""
"""
num = 3
den = 2
count = 0
i = 1
while i <= 1000:
if isNumeratorLonger(num=num, den=den):
count += 1
nextNum = num + (den * 2)
nextDen = num + d... |
def powerOf(n, p):
"""
"""
r = 1
while p > 0:
r *= n
p -= 1
return r
def getDigitalSum(n):
"""
"""
l = ''.join(str(n))
l = [int(x) for x in l]
return sum(l) if len(l) > 0 else 0
if __name__ == "__main__":
print powerOf(3, 2)
print powerOf(3, 3)
lo... |
'''
Created on 2017/12/17
@author: kshig
'''
for n in range(2, 100):
for x in range(2, n):
if n % x == 0:
print(n, " = ", x, "*", n//x)
break
else:
print(n, "is a prime number!") |
#Database of words.
class Wordbank(object):
def __init__(self, words=[]):
self.word_to_index = {"":-1, ".":-1, "?":-2, "!":-3}
self.index_to_word = {-1:".", -2:"?", -3:"!"}
self.num_words = 0
self.add(words)
def __len__(self):
return self.num_words
def __getit... |
from wheel import Wheel
from table import Table
from bin_builder import BinBuilder
from bet import Bet
import sys
class Player(object):
"""Base class for players."""
def __init__(self, table):
self.stake = None
self.rounds_to_go = sys.maxint
self.table = table
self.last_outcom... |
class car(object):
def __init__(self, price, speed, fuel, mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
#self.displayall()
if price > 10000:
self.tax = .15
else:
self.tax = .12
self.dis... |
#!/usr/bin/env python
from subprocess import Popen, PIPE
import sys
#import list_all_cars
import get_cars
import login
import solve_car
def solved_file_name():
return "solved_cars"
def read_solved_file():
try:
solved_file = open(solved_file_name())
solved_list = [line.strip() for line in solved_file.re... |
#selection
def selection(arr):
# 0부터 n-1까지 반복
for i in range(0, len(arr)-1):
#i값을 잡고 min으로 둔 다음 min값을 계속 찾는다
min = i
# i+1부터 n까지 반복, 가장 작은 값을 찾아 min에 저장
for j in range(i, len(arr)):
if arr[min] > arr[j]:
min = j
# i번째 인덱스와 제일 작은 값을 swap
... |
import unittest
from typing import cast
from monkey import lexer
from monkey import obj as objmod
from monkey import parser
from monkey import evaluator
class TestEvaluator(unittest.TestCase):
def test_eval_integer_expression(self):
tests = [
("5", 5),
("10", 10),
("-5"... |
from random import shuffle
class Game:
def __init__(self):
"""Return the inital state of the board."""
x = list(range(1, 9))
x.append('X')
shuffle(x)
self.board = [x[0:3], x[3:6], x[6:]]
def terminal_state(self):
"""Return True if game has ended... |
def parse_json(filename):
if not isinstance(filename, str):
return 'Filename must be a string'
try:
with open(filename, 'r') as myfile:
line = str(myfile.readlines())
result = 0
temp = ""
for key, value in enumerate(line):
"""
... |
def computegrade(score):
if score >= 0.9:
grade = 'A'
elif score >= 0.8:
grade = 'B'
elif score >= 0.7:
grade = 'C'
elif score >= 0.6:
grade = 'D'
else:
grade = 'F'
return grade
marks = float(input('Enter score: '))
print(f'GRADE: {computegrade(marks)}')... |
#calculating total number of items and average
numCounter = 0
total = 0.0
while True:
number = input("Enter a number: ")
if number == 'done':
break
try :
num1 = float(number)
except:
print('Invalid Input')
continue
numCounter = numCounter+1
total = total + num1
p... |
def computepay(hour, rate):
if hour <= 40:
pay = hour * rate
else:
pay = ((hour - 40) * (1.5 * rate)) + (40 * rate)
return pay
hours = float(input('Enter Hours: '))
rates = float(input('Enter Rate: '))
print(f'Pay: {computepay(hours, rates)}')
|
import random
import letterfrequencychart
alphabet = "abcdefghijklmnopqrstuvwxyz"
def make_mono_sub(message):
ciphertext = ""
new_alphabet = ""
message = message.lower()
random_letter = random.randint(0,25)
while len(new_alphabet) < 26:
if alphabet[random_letter] not in new_alphabet:
... |
# 4. Найти значение минимального элемента списка
import random
n = int(input("Input list size:\n"))
A = []
for i in range(n):
A.append(random.randint(0, 99))
print(A)
B = set(A)
A = list(B)
print(A[0])
|
import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
... |
def multiplicationTable(number):
for i in range(1, 11):
print(number, "x", i, " : ", number * i)
number = input("Enter number : ")
number = (int)(number)
print("Multiplication Table for ", number)
multiplicationTable(number)
|
def compoud_interest(p, r, t):
print("Principal Amount : ", p, "INR")
print("Rate of Interest : ", r, "%")
print("Time Duration :", t, "years")
interest = (float)(p) * pow((1 + (float)(r) / 100), (int)(t))
print("Compound interest :", interest)
p = input("Enter Principal amount :")
r = input("Ent... |
def cube(n):
temp = (int)(n)
sum = 0
while temp != 0:
digit = (int)(temp % 10)
sum += digit * digit * digit
temp = (int)(temp / 10)
if (int)(n) == (int)(sum):
return True
else:
return False
testcases = input("Enter number of testcases :")
t... |
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
import numpy as np
from sklearn.cluster import KMeans
from sklearn import preprocessing
import pandas as pd
'''
Pclass Passenger Class (1 = 1st; 2 = 2nd; 3 = 3rd)
survival Survival (0 = No; 1 = Yes)
name Name
sex Sex
age Age
... |
a = int(input())
b = int(input())
c = int(input())
def add(first,second):
summ = first + second
return summ
s = add(a,b)
def subs(the_sum,third):
f = the_sum- third
return f
final = subs(s,c)
print(final)
|
class Article:
def __init__(self,title,content,author):
self.title = title
self.content = content
self.author = author
def Edit(self, new_content):
self.content = new_content
def ChangeAuthor(self, new_author):
self.author = new_author
def Rename(self, new_title... |
passw = input()
def Is_Valid(password):
valid_length = False
two_digits = False
only = True
digit = 0
let_dig = 0
if len(password) >= 6 and len(password) <= 10:
valid_length = True
else:
print('Password must be between 6 and 10 characters')
for i in password:
if ... |
text = input()
strength = 0
i = 0
while i < len(text):
symbol = text[i]
if symbol == '>':
strength += int(text[i + 1])
i += 1
continue
if strength > 0:
text = text[:i] + text[i+1:]
i -=1
strength -=1
i +=1
print(text) |
import re
n = int(input())
for _ in range(n):
barcode = input()
pattern = "^@[#]+[A-Z][a-zA-Z0-9]{4,}[A-Z]@#+$"
matches = re.findall(pattern,barcode)
if matches:
pb = '(?P<prod>\d)'
m = re.findall(pb,barcode)
if m:
print(f"Product group: {''.join(m)}")
else:
... |
#Sinartisi Roman
def roman(num):
#arithmoi
numbers = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
#Simbola
romans = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
i = 0
res = ""
while num > 0:
for j in range(num//numbers[i]):
... |
# convert file path
def make_pythonreadable_windows_path(windows_path = [r'C:\Users\mehedee\Documents']):
python_path = ''
for character in windows_path:
if character == '\\':
python_path += '/'
else:
python_path += character
return python_path
print(make_python... |
# 1. revarse string using one command
a = "ilovepython"
print a[::-1]
# out: nohtypevoli
# 2. last value of list
a2 = [1,2,3,4,5,6]
a2str = 'abcd'
print(a2[-1])
print(a2str[-1])
#out : 6
#d
# 3. list to string with separator
row = ["1", "bob", "developer", "python"]
print(*row,sep='.')
#out: 1.bob.developer.... |
# -*- coding: utf-8 -*-
# Extracting and Parsing Web Site Data (Python)
# prepare for Python version 3x features and functions
from __future__ import division, print_function
# import packages for web scraping/parsing
import requests # functions for interacting with web pages
from lxml import html # functio... |
#Напишите функцию ask_user(), которая с помощью input() спрашивает пользователя “Как дела?”, пока он не ответит “Хорошо”
#Создайте словарь типа "вопрос": "ответ", например: {"Как дела": "Хорошо!", "Что делаешь?": "Программирую"} и так далее
#Доработайте ask_user() так, чтобы когда пользователь вводил вопрос который ест... |
"""
Write a function that takes in a two-dimensional list (a list that contains
lists) and returns a new list which contains only the lists from the original
which:
1. were not empty
2. have items that are all of the same type
You can assume that the lists inside the list will only contain integers or
strings. Also, ... |
"""
Prog: Lab1.py
Auth: Oleksii Krutko, IO-z91
Desc: Computer graphics Lab 1. 2020
"""
from math import *
import graphics as glib
import matplotlib.pyplot as plt
import turtle
def transform_point_perspective(point_original, perspective_center):
"""
Transforms a 3d point to a 2d using perspective tra... |
#Import libs
import matplotlib.pyplot as plt
import seaborn as sns
#Load the data
data = sns.load_dataset("mpg")
#print head
print(data.head())
#Generate the box plot
sns.boxplot(x="cylinders",y="mpg", data=data)
#display plot
plt.show()
|
import numpy
time_format = '%Y-%m-%d %H:%M:%S.%f'
def hr_avg(heart_rates):
"""
Calculates the average heart of an input list
:param heart_rates:
:return: avg
"""
avg = numpy.mean(heart_rates)
return avg
def find_cutoff_index(time_input, heart_rate_times):
"""
Finds the index in... |
import sqlite3
# Данных
# Базы Данных
# SQL - язык работы с данными
# sqlite - версия / отдельная база данных
# Таблица "Люди"
# id | Имя | Возраст |
# 0 | Max | 16
# 1 | Olga | 41
# Создаем объект соединения
with sqlite3.connect('try_slite.db') as con:
# выполнить к... |
text = '''
Hello, Bill!!
Send me some info about lesson.
'''
words = text.split()
lev_syms = [ ',', '!', '.' ]
for word in words:
if 'i' in word or 'o' in word:
# if len(word) > 2:
# word = word[:3]
# for sym in lev_syms:
# word = word.replace(sym, '')
fo... |
# Echo server program
import socket
def serve(HOST, PORT):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
# Резервируем адрес и порт в системе
s.bind((HOST, PORT))
# Ждать соединений
s.listen(1) # одновременных соединений может быть не больше 1
while True:
... |
# # про список
# if "hello" in s:
# s.append('buy')
lst = [1, 2, 3]
#print( str(lst) )
lst_2 = []
for sym in lst:
sym = str(sym)
lst_2.append(sym)
lst_2 = set(lst_2)
s = ';'.join(lst_2)
print(s)
#s = '1;2;3'
x = 0
for i in range(12):
for j in range(20):
x += i * j
if ... |
lst = [ "hello", "buy", "item" ]
# Список с длинами слов:
lst2 = [ len(i) for i in lst ]
print( lst2 ) |
# Функция внутри функции
def func():
x = 100
def other_func():
print('hello!')
other_func()
func()
# Полезный вариант
def func(count):
def other_func(n): # принимает на вход n
print('hello!', n)
for i in range(count):
other_func(i)
func(1000)
# global и nonl... |
class Transport:
price = 0
speed = 0
def time(self, way):
return way / self.speed
class Taxi(Transport):
price = 45
speed = 60
class Tram(Transport):
price = 30
speed = 40
class Trolleybus(Transport):
price = 30
speed = 50
class Autobus(Transport):
price = 30
... |
# coding: utf-8
# 1. Исправить ошибки в этом программном коде
n = 0
def smart_task():
n += 1
print( 'start of smart_task #{}'.format('n') )
def other_task(): ## +
param_1 = None,
param_2 = None
if param_1 == None:
return None
print... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.