text
stringlengths
37
1.41M
# You are given a string of length N and a parameter k. # The string can be manipulated by taking one of the first k letters and moving it to the end. # Write a program to determine the lexicographically smallest string that can be created after an unlimited number of moves. # For example, suppose we are given the s...
#You are given an string representing the initial conditions of some dominoes. Each element can take one of three values: # L, meaning the domino has just been pushed to the left, # R, meaning the domino has just been pushed to the right, or # ., meaning the domino is standing still. # Determine the orientation of eac...
# A fixed point in an array is an element whose value is equal to its index. # Given a sorted array of distinct elements, return a fixed point, if one exists. Otherwise, return False. # For example, given [-6, 0, 2, 40], you should return 2. Given [1, 5, 7, 8], you should return False. test_array = [-6,0,2,40] def arr...
# Complete the repeatedString function in the editor below. # It should return an integer representing the number of occurrences of a in the prefix of length in the infinitely repeating string. # repeatedString has the following parameter(s): # s: a string to repeat # n: the number of characters to consider s = "a...
#how would you find all pairs of an integer array who's sum is equal to a given number. import random test_array = [] target_sum = 500 numbers_sum = [] def fill_array(): #fills an empty array with 100 random numbers from 1-1000 for i in range(0,101): random_int = random.randint(1,1001) test_arra...
# Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, # how many ways can we make the change? The order of coins doesn’t matter. # For example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}. # So out...
# import depending libraries import time import pandas as pd import numpy as np # dictonary with city names and their corresponding csv data files CITY_DATA = {'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv'} # dictonary with all the possible ...
#!/usr/bin/env python # coding=utf-8 """ Estimate cost into local heating network (LHN) Cost are valid for pipe-combination of inlet and return flow. You do NOT need to multiply the resulting cost with factor 2! """ from __future__ import division import math import warnings import numpy as np import matplotlib.pyplo...
from sys import stdin top = 5003 vec = [0,1] for i in range(2,top): vec.append(vec[i-1]+vec[i-2]) """ def fibonacci(n): if n == 1: return 1 elif n == 0: return 0 elif n in dic: return dic[n] else: dic[n] = fibonacci(n-1)+fibonacci(n-2) return dic[n] """ def ma...
from sys import stdin def initialize(graph, source): d = {} # Stands for destination p = {} # Stands for predecessor for node in graph: d[node] = float('Inf') # We start admiting that the rest of nodes are very very far p[node] = None d[source] = 0 # For the source we know h...
# functions - starts with def def print_max(a,b): if a>b: print('a is maximun') elif a==b: print('a is equal to b') else: print('b is maximum') # directly pass the literal values print_max(3,4) x = 5 y = 7 # pass variables as arguments print_max(x,y) def sayHello(...
# -------------- #Header files import pandas as pd import numpy as np import matplotlib.pyplot as plt #Reading of the file data=pd.read_csv(path) # Code starts here # Replacing the '-' with 'Agender' in gender column data['Gender'].replace('-','Agender',inplace=True) # Plotting the Distribution of Ge...
######################################################################## # # Functions for calculating Total Return, Annualized Returns, etc. # ######################################################################## # # This file is part of FinanceOps: # # https://github.com/Hvass-Labs/FinanceOps # # Published under t...
import pandas as panda import numpy as np def create_panda_data_frame(): ''' there are two primary data structure in pandas 1. panda series : container for scalar values. NOT SIZE MUTABLE 2. panda data frame : container for series. COLUMNS CAN BE ADDED,MUTABLE panda...
def group_by(arr, *, unique=True, key): grouped = {} for el in arr: k = key(el) if unique: assert k not in grouped, "The given key is not unique for the array" grouped[k] = el else: if k not in grouped: grouped[k] = [] gro...
import pandas as pd import numpy as np import matplotlib.pyplot as plt def SexSurvived(df): group = df.groupby(['Sex']).Survived.count() return group['male'], group['female'] def percentage(function, ti): male, female = function(ti) total = male + female return calculate(male, total), cal...
# Task 1. # # Write a decorator which wraps functions to log function arguments and the return value on each call. # Provide support for both positional and named arguments (your wrapper function should take both *args and **kwargs # and print them both): # # >>> func(4, 4, 4) # you called func(4, 4, 4) # it returned ...
""" eg: 单例使用场景 打印机 回收站 音乐播放器 单例模式 目的 让类创建的对象 在系统中只有唯一的一个实例 每一次执行 类名() 放回的对象 内存地址是相同的 """ class musicplayer(object): #创建对象时候 该方法自动调用 def __new__(cls, *args, **kwargs): print("创建对象时候默认使用的函数 进行内存空间的分配 必须要returne 返回") #为对象分配空间 instance = super().__new__(cls) #返回对象的引用 return instance def...
#! /usr/bin/python class Employee: 'This is optional document string' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print('Total number of employee: ',Employee.empCount) def displayEmployee(self): print('Name...
#! /usr/bin/python # My Way of doing it in first shot mylist = [1, 2, 3, 4, 5, 6, 7] listlenght = len(mylist) number = 0 if listlenght > 0: for itr in mylist: number += itr else: print('Input list is not having any element.') exit(0) print("Average of list is : ",number/listlenght) ## Doing other way, explain...
# -*- coding: utf-8 -*- # @Time : 2018/7/28 下午3:38 # @Author : yidxue class A(object): def __init__(self, name, age): self.name = name self.age = age def __delattr__(self, *args, **kwargs): print('call func del attr') return object.__delattr__(self, *args, **kwargs) a = ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019-04-15 17:43 # @Author : erwin import numpy as np import pandas as pd from common.util_function import * data = np.array([[1, 2, 3, 4], [4, 5, 6, 8], [2, 3, 5, 9]]) df = pd.DataFrame(data=data, index=[2, 1, 3], columns=['...
# -*- coding: utf-8 -*- if __name__ == '__main__': ''' 三目运算符 ''' print(True if 5 > 3 else False) ''' 类型判断 ''' dic = {"JOINMETHOD": {"ActiveX": "1", "Extension": {"USERTYPE": {"NEW": "1", "RETURN": "0"}}}} print(isinstance(dic["JOINMETHOD"], dict)) print(isinstance([1, 2, 3], li...
# -*- coding: utf-8 -*- import time class TimeParser(object): def __init__(self): pass def parse_time(self, time_str): """解析时间字符串, 返回绝对时间戳 :param time_str: 支持 Unix 时间戳, '%Y-%m-%d %H:%M:%S', '1m', '2h', '-3d', 'now' 几种格式 """ is_unix_ts, timestamp = self._check_unix_ts(...
# -*- coding: utf-8 -*- # @Time : 2018/7/29 上午11:59 # @Author : yidxue from common.util_function import * print_line("定义list") ls = [1, 2, 3] print_br(ls) print_line("基于map方式,生成一个list") dic = {"a": 1, "b": 2, "c": 3, "d": 4} print(map(lambda item: item[1], dic.items())) print_line("基于列表推导生成list。即根据一份列表制作另一份列表。")...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/9/25 9:59 AM # @Author : Erwin import pandas as pd pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) from common.util_function import * df = pd.read_csv('./data/count-stat.csv', sep=",", he...
def Add(x,y): # Iterate till there is no carry while (y != 0): # carry now contains common # set bits of x and y carry = x & y # Sum of bits of x and y where at # least one of the bits is not set x = x ^ y # Carry is shift...
""" Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. Suppose the following input is supplied to the program: without,hello,bag,world Then, the output should be: bag,hello,without,world """ items=[x for ...
""" computational-art creating artistic images with recursion in python. @author: Oscar Zhang """ import random import math from PIL import Image def build_random_function(min_depth, max_depth): """Build a random function. Builds a random function of depth at least min_depth and depth at most max_depth....
""" Rename files in a directory in a structured way Arguments: input_folder - the folder that houses the files you want to copy output_folder - a user specified folder that exists which is the destination of copied files label - a description that creates a new name along with a count """ import os import pandas as...
# Lists that I will need for the whole program to_do_list = [] to_do_time = [] # Function to ask what is on the to-do list and fill the lists with the information # Does not take an argument, but does ask the user for an input inside the function # Returns the number of items on the to-do list def get_my_schedule(): ...
from threading import RLock class BankAccount(object): def __init__(self): self._balance = None self._lock = RLock() def error_if_closed(self) -> None: """ Raise a ValueError if the account is already closed. """ if self._balance is None: raise Val...
from food import Food class Meat(Food): def cook(self): print("The meat is cooking :)") steak = Meat('Sirloin', 'Tasty') steak.describe(steak) steak.cook() print(steak)
def merge_sort(a, verbose=False): global inversions if verbose: print("Splitting ", a) if len(a) > 1: mid = len(a) // 2 left = a[:mid] right = a[mid:] merge_sort(left, verbose) merge_sort(right, verbose) i = 0 j = 0 k = 0 wh...
# Uses python3 import sys MULTIPLICATIONS = [2, 3] def count_operatiosn(n): # Assuming the first coin is 1 values = [0] * (n+1) operations = [0] * (n+1) for i in range(2, n+1): values[i] = values[i-1] + 1 for mult in MULTIPLICATIONS: if i % mult == 0: tes...
from math import * def isPrime(n): i = 2 while(i**2 < n+1): p = n%i if p == 0: #print("% 3d est un diviseur de % d " %(i,n) ) return False i+=1 return True print(isPrime(1001)) #crible à revoir def eratosthene(n): liste = [i for i in range...
import os from pygit2 import Repository ''' A simple git command to quickly clean out your old branches. ''' if os.path.exists("./.git"): local_repo_name = os.getcwd() + "\\.git" repo = Repository(local_repo_name) print() branches_to_remove = [] for branch in repo.branches.local: if (branch == "master" or...
import random import os import sys age = 21 if age > 16 : print("You are old enough to drive") else : print('You are not old enough') if age >= 21 : print('You can drink') elif age >= 16 : print("You can drive") else : print("You're not old enough") if ((age >=1) and (age <= 18)): print("Y...
def countdown(n): if n <= 0: print("blastOff") else: print(n) countdown(n-1) #countdown(3) def print_n(s,n): if n<=0: return name() print_n(name,n-1) def name(): print('my name is feisal') #print_n(name,5) def fermat(a,b,c,n): if n>2: if (a**n + b...
def converter(number): answer= number//2 remainder=number%2 print(remainder) if answer != 0: converter(answer) converter(58)
#Python dictionary dic={"Saddaam":1213, "Rayhan":1245} print(dic) #Length of the Dictionary print("Length Of the Dictionary: ",len(dic)) #Another Dictionary dic2={"islam":0000, "Biology": 4587, "Human Rights":6525,"Political Science":1542} print(dic2) print("Length of the Second Dictionary",len(dic2)) ...
# Zadání: ######### # # Pokud pole o délce N, obsahuje všechna čísla od 0..N-1 právě jednou, pak toto # pole kóduje permutaci tak, že první prvek se zobrazí na místo, kde se v poli # nachází 0, druhý prvek na místo, kde se v poli nachází 1,… # # Pole [0, 1, 2, 3], kóduje identickou tzv. jednotkovou permutaci o čtyřech...
# Zadání: ######### # # Opravte následující kód: """" step = 0.1 sum = 0 for is in range(1,11): sum += step if (suma == is/10): print("Plati",sum,"rovno", is/10) else: print("Neplati",sum,"nerovno", is/10) """ step = 0.1; sum = 0; for i in range(1,11): sum += step; if (sum == i/10):...
# Zadání: ######### # # Napište funkci printPoly,která vypíše polynom, přičemž mocniny bude tisknout # znakem '^'. # # Pokud je nějaký koeficient nulový, příslušný člen se nevypíše # # Příklad: printPoly( [ 1, 1, 0, -2] ) vytiskne 1 + x - 2 x^3 #########################################################################...
# Zadání: ######### # # Napište funkci polyMulti, která násobí dva polynomy (polynomy mohou mít různé # stupně). # # Příklad volání: polyMulti( [1, 1], [-2, 1] ) vrátí [-2, -1, 1] neboť # (x+1)(x−2)=x^2−x−2 ############################################################################### def polyMulti( x, y ): """...
class MinHeap: """ binární halda, implementovaná pomocí metod """ def __init__(self): self.heap = [] # indexujeme od nuly def bubble_up(self,i): """ probublá prvek 'i', zajistí splnění vlastnosti haldy """ while i>0: j=(i-1)//2 # index rodiče i...
#!/usr/bin/python3 # Jaskaran import sys import re def printfunc(): print("hello") previous = None sum = 0 str_out = '' # We are usign a string to k for line in sys.stdin: key, value = line.split('\t') if key != previous: if previous is not None: str_out = str_out.replace("\n","") print('\n') print(str...
def nthSuperUglyNumber(n, primes): """ :type n: int :type primes: List[int] :rtype: int """ factors = [] pl = len(primes) for i in range(0, pl-1): f = primes[i] while f < primes[pl-1]: factors.append(f) f = f*primes[i] factors.append(primes[pl-...
from datetime import date #Class class Customer: def __init__(self,customerID, customerName, customerEmail): self.customerID = customerID self.customerName = customerName self.customerEmail = customerEmail def getInformation(self): print("CustomerID: ", self.customerID, "Cu...
from itertools import count from math import factorial def fact(n): for el in count(1): yield factorial(el) x = 0 n=int(input("Введите значение n: ")) for i in fact(n): if x < n: print(i) x += 1 else: break # Реализовать генератор с помощью функции с ключевым словом yield...
v = int(input("Введите значени выручки, руб: ")) i = int(input("Введите значени издержек, руб: ")) pribil=v-i p=abs(pribil) rent=pribil/v if pribil<0: print(f"Убыток фирмы: {p} руб") else: print(f"Прибыль фирмы: {pribil} руб") print(f"Рентабильность фирмы: {rent}") ch = int(input("Введите численность сотр...
lst1=[2, 2, 2, 7, 23, 1, 44, 44, 3, 2, 10, 7, 4, 11] lst2 = [lst1[i] for i in range(1,len(lst1)) if i in range(1,len(lst1)) if lst1.count(lst1[i])==1] print(f"Исходный список: {lst1}") print(f"Новый список: {lst2}")
# implement binary search algorithm to search an element in an array: def binary_search(arr, ele): """Implementation of Binary Search Algorithms for list bases Data Structure""" if type(arr) != list or len(arr) == 0 or ele is None: return -1 return _binary_search_impl(arr, 0, len(arr) - 1, ele) ...
class Board: #WHEN REFERENCING GRID: #grid[x][y] (x is row, y is column). (0,0) is top left) colormode = True #SET THIS TO FALSE IF WINDOWS USER def __init__(self): self.grid = [] for x in range(10): self.grid.append([0]*10) def fill_count(self): c = 0 fo...
def clean_input(input_text): return input_text.replace("\n", "").replace("\r", "") def count_lines(input_file): with open(input_file, 'r', 1024, encoding="utf8", errors="ignore") as open_file: count = 0 while True: if open_file.readline(): count += 1 else...
# 字典 一系列无序元素的组合,其长度大小可变,元素可以任意地删减和改变 # 字典是一对键(key)和值(value)的配对 tel = {'jack': 14568, 'xxx': 5974} print(tel) print(tel['jack']) del tel['xxx'] print(tel) tel['aaaa'] = 456213 print(tel) print(list(tel)) print(sorted(tel)) print(tel) print('aaaa' in tel) print('aaaa' not in tel) a = [tel[x] for x in sorted(tel)] p...
# name = input('your name:\n') # gender = input('you are a boy?(y/n)\n') # # welcome_str = 'Welcome to the matrix {prefix} {name}' # welcome_dic = { # 'prefix': 'Mr.' if gender == 'y' else 'Mrs.', # 'name': name # } # print('authorizing...') # print(welcome_str.format(**welcome_dic)) import re # a = input() # ...
a = [1, 2, 3, 4, 5] b = a[1:3] #슬라이싱 기법으로 리스트생성 print(b) print(a) del a[2:] #list 요소 삭제 print(a) a.append(0) # list 요소 추가 print(a) a.sort() # 요소 오름차순 정렬 print(a) a.reverse() # list 역순으로 뒤집기 print(a) print(a.index(0)) # 요소 위치 반환 : index a.insert(0, 4) # 첫번째 요소(0)에 값(4) 추가 삽입 print(a) a.remove(1) # 요소중에 맨처음 나오는 값(1)...
a = [1, 2] try: a[3] except IndexError as e: print(e) f = open('foo.txt', 'w') try: print('aaaaa') finally: f.close() #여러 개의 오류 처리하기 try: a = [1,2] print(a[1]) 4/0 except ZeroDivisionError: print("0으로 나눌 수 없습니다.") except IndexError: print("인덱싱할 수 없습니다.") try: a = [1,2] p...
# Q1 hong = {"국어":80, "영어":75, "수학":55} print(len(hong)) print(hong["국어"]) sum = hong["국어"] + hong["영어"] + hong["수학"] print(sum) average = sum / len(hong) print(average) # Q2 num = 13 if num % 2 == 1 : print("홀수") else: print("짝수") # Q3 pin = "881120-1068234" yyyymmdd = pin[0:6] print(yyyymmdd) num = pin[0:6]...
# 보통 1개의 프로세스는 한 가지 일만 하지만 # 스레드를 사용하면 한 프로세스 안에서 2가지 또는 그 이상의 일을 동시에 수행할 수 있다. """ # test1 import time def long_task(): # 5초의 시간이 거리는 함수 for i in range(5): time.sleep(1) print("working:%s" %i) print("Start") for i in range(5): long_task() print("End") """ """ # test2 --> threads가 뭔지 잘 몰라서 ...
# for 변수 in 리스트(또는 튜플, 문자열): # 수행할 문장1 # 수행할 문장2 # ... test_list = ['one', 'two', 'three'] for i in test_list: print(i) a = [(1,2), (3,4), (5,6)] #튜플선언 for (first, last) in a: print(first + last) # range 함수 a = range(10) print(a) # range(0, 10) : 0~9 add = 0 for i in range(1, 11): add = a...
class father(): # 부모 클래스 def handsome(self): print("잘생겼다") class brother(father): # 자식클래스(부모클래스) 아빠매소드를 상속받겠다 '''아들''' class sister(father): # 자식클래스(부모클래스) 아빠매소드를 상속받겠다 def pretty(self): print("예쁘다") def handsome(self): '''물려받았어요''' brother = brother() print('1') brothe...
# 모듈이란 함수나 변수 또는 클래스를 모아 놓은 파일이다. # 다른 파이썬 프로그램에서 불러와 사용할 수 있게끔 만든 파이썬 파일 # import (모듈내임) # mod1.py 로 저장했다면 # def add(a, b): # return a + b # def sub(a, b): # return a - b import mod1 import mod2 from mod1 import add, sub #from mod1 import * print(add(1, 4)) print(sub(4, 2)) PI = 3.141592 class Math: def ...
def foo (id , name): print(id, name) id = name print(id) name = id print(name) return (id, name) id = 3 name = "kim" id, name = foo(id, name) print("id = ", id, ", name = ", name) a = [1, 2, 3, 4, 56, 3, 4, 34] def maybeBubbleSort(list1): sorted = False while (not sorted) : s...
def retornos(retornos): # print para observar los valores return print(retornos) def game(puntos): # validar que es una lista if type(puntos) == list: #creo una nueva lista para almacenar solo los 3 elementos mas altos de la lista maximos = [] #aqui obtengo el valor mas alto...
from tkinter import * # tkinterモジュールのimport W, H = (600, 600) # canvasの幅と高さ def display(canvas): # 描画関数 ''' canvas - 描画するcanvas 11本の放射上の線分を描画する ''' points = ((W/60, H), (W/20, H), (W/8, H), (W/4, H), ( W/2, H), ( W, H), ( W, H...
#Author :> Abhishek Das #Code Writer :> silentace(Author) #Date :> 02/03/2021 #Location :> India/West Bengal from playsound import playsound #import play sound to play msuic from os import listdir #import listdir for music search and print the list option = input("Add Music Path: ")+"\\" option = optio...
hungry = input("are you hungry?") if hungry == 'yes': print("eat samosa ") print("eat pizza also") print("remember junk food not good for health") else: print("do your homework") print("life is good so for ")
from __init__ import time_elapsed, arr @time_elapsed def binary_search(arr, low, high, key): while (low <= high): mid = (low+high) >> 1 if arr[mid] < key: low = mid+1 elif arr[mid] > key: high = mid-1 else: return mid return False print(bina...
class newNode(): def __init__(self, data): self.data = data self.left = None self.right = None """ Inorder traversal of a binary tree""" ''''def inorder(temp): if (not temp): return inorder(temp.left) print(temp.data, end=" ") inorder(temp.right)'''...
from abc import ABC,abstractmethod class Sentence: def __init__(self,words:[str]): self.__words = words def __str__(self) -> str: sentenceString = "" for word in self.__words: sentenceString += word + " " return sentenceString[:-1] class FormattedSentence(ABC): ...
from abc import ABC, abstractmethod from board import Board class Command(ABC): @abstractmethod def execute(self): pass @abstractmethod def undo(self): pass class DashUpCommand(Command): def __init__(self, board: Board): self.__board: Board = board self.__backU...
######INPUTS###### ######pary input###### charnumber = int(input("Number of characters in the party? ")) count = 0 charlevels = [0,0,0,0,0,0,0,0,0,0] while count < charnumber and charnumber > 1: print("Character %d is what level? " % (count +1)) charlevels[count] = int(input(" ")) count += 1 if cha...
#!/usr/bin/python from math import sqrt import json # A simple class to read in a JSON file that holds list of systematic # groups. This class reads in the JSON file, and inverts the # dictionary to look up groups for systematics. class SystDictionary(): _groups = [] #List of all groups _systematics = [...
""" Graph impl - add_vertex(vertex) - remove_vertex(vertex) - connect_vertex(a,b) - disconnect_vertex(a,b) """ from Stack import Stack from Queue import Queue import time class Vertex: def __init__(self,value): self.value = value self.hit = False self.parent = None def __eq__(self,...
def bsearch(arr, item): reversed = True if arr[0]>arr[len(arr)-1] else False if len(arr) == 2: if item == arr[0]: return 0 elif item == arr[1]: return 1 else: return None mid = len(arr)//2 if arr[mid] == item: return mid elif item >...
from utils.linked_lists import * def weave(ll1, ll2): ''' Apply 'Runner Technique': one pointer p1 (the fast pointer) move every two elements for every one move that p2 makes. When p1 hits the end of the linked list, p2 will be at the midpoint. Then, move pl back to the front and begin...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/4/1 0001 下午 12:41 # @Author : StalloneYang # @File : task_flower.py # @desc:仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身. # (例如:1^3 + 5^3 + 3^3 = 153),1+125+27 # 用Python算出100-1000的所有水仙花数,打印出来 # n位数,123就是3位数,1212就是四位数,12345就是五位数。。。。所以n就...
# coding: utf-8 import sys import csv # 存csv文件 def savecsv(path, data): csvfile = file(path, 'wb') writer = csv.writer(csvfile) for row in data: writer.writerow(row) csvfile.close() def savecsv_withdelimiter(path, data, delimiter_str): csvfile = file(path, 'wb') writer = csv.writer(csvfile, delimiter=delimit...
#Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. (Hint: remember to use the user input lessons from the very first exercise) import random,sys a = random.randint(1, 9) b=0 while(1): b=input("i...
def double(a): b=[] for i in a: if(not(i in b)): b.append(i) return b a=[1,2,3,4,5,1,2,8,5,3,6,78,4,2,4,1,9] b=double(a) print(b)
#Take a list, say for example this one: #a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] #and write a program that prints out all the elements of the list that are less than 5. a=[1,1,2,3,5,8,13,21,34,55,89] for i in range(len(a)): if(a[i]<5): print(str(a[i])+" ")
def shell_sort(arr): inc = len(arr) // 2 while inc: for i, el in enumerate(arr[inc:], inc): while i >= inc and arr[i - inc] > el: arr[i] = arr[i - inc] i -= inc arr[i] = el inc = 1 if inc == 2 else inc * 5 // 11
# -*- coding: utf-8 -*- # Wyznaczy listę słów, które pojawiają się w tekście z jednego pliku, a nie pojawiają się w tekście z pliku drugiego przy pomocy algorytmu Boyer-Moore import os def read_to_string(path): with open(path, 'r', encoding="utf-8") as file: text = file.read() text = text.lower() ...
class Line(object): def __init__(self, *args, **kwargs): """ Simple Representation of a Line """ # TODO: This could be refactored, but it is probably fine for now for clarity # TODO: Validate call args for type # TODO: Catch infinite slope case i.e. div by 0 ...
"""The module provides functions to compute different kinds of returns of stocks.""" from typing import Any import numpy as np import pandas as pd from finquant.data_types import ( ARRAY_OR_SERIES, FLOAT, INT, NUMERIC, SERIES_OR_DATAFRAME, ) from finquant.type_utilities import type_validation ...
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/UwdBQ/khanoiskiie-bashni # Ханойские башни # Головоломка “Ханойские башни” состоит из трех стержней, пронумерованных # числами 1, 2, 3. На стержень 1 надета пирамидка из n дисков различного # диаметра в порядке убывания диаметра (снизу н...
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/Z8IA2/maksimum-posliedovatiel-nosti # Максимум последовательности # Последовательность состоит из целых чисел и завершается числом 0. # Определите значение наибольшего элемента последовательности. n = int(input()) max = n while n ...
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/1qAPB/slieduiushchieie-chietnoie # Следующее четно n = int(input()) print(n - (n % 2) + 2)
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/7886R/szhatiie-spiska # Сжатие списка # Дан список целых чисел. Требуется “сжать” его, переместив все ненулевые # элементы в левую часть списка, не меняя их порядок, а все нули - в правую # часть. Порядок ненулевых элементов изменять ...
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/4JHKe/chastotnyi-analiz # Частотный анализ # Дан текст. Выведите все слова, встречающиеся в тексте, по одному на каждую # строку. Слова должны быть отсортированы по убыванию их количества появления в # тексте, а при одинаковой частоте ...
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/QEiwQ/chislo-sochietanii # Число сочетаний # По данным целым числам n и k (0≤k≤n) вычислите C из n по k. # Решение оформите в виде функции C(n, k). # Для решения используйте рекуррентное соотношение: # С(n, k) = С(n - 1, k) + С(n - 1, k...
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/5tQ5s/shokoladka # Шоколадка # Шоколадка имеет вид прямоугольника, разделенного на n×m долек. # Шоколадку можно один раз разломить по прямой на две части. # Определите, можно ли таким образом отломить от шоколадки часть, состоящую ровн...
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/KxNAx/klaviatura # Клавиатура qty = int(input()) keys_endurance = tuple(map(int, input().split())) total_keystrokes = int(input()) keystrokes = tuple(map(int, input().split())) keystrokes_by_key = [0] * qty for key in keystrokes...
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/Ju34T/pieriestavit-min-i-max # Переставить min и max # В списке все элементы попарно различны. Поменяйте местами минимальный и # максимальный элемент этого списка. data = list(map(int, input().split())) min_index = 0 max_index = ...
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/COVcr/nomier-poiavlieniia-slova # Номер появления слова # Во входном файле (вы можете читать данные из файла input.txt) записан текст. # Словом считается последовательность непробельных подряд идущих символов. # Слова разделены одним и...
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/6I71w/maksimal-noie-chislo-podriad-idushchikh-ravnykh # Максимальное число подряд идущих равных # Дана последовательность натуральных чисел, завершающаяся числом 0. # Определите, какое наибольшее число подряд идущих элементов этой # посл...
##https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/JAMsA/obrashchieniie-chisla/submission ## ##Обращение числа ##Переставьте цифры числа в обратном порядке . def reverse_number(n): result = 0 while n > 0: result = result * 10 + n % 10 n //= 10 return resu...
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/30kXq/slieduiushchieie-i-priedydushchieie # Задание по программированию: Следующее и предыдущее # Напишите программу, которая считывает целое число и выводит текст, аналогичный приведенному # в примере (важно в точности соблюдать вывод...