text
stringlengths
37
1.41M
class Solution: def restoreString(self, s: str, indices: List[int]) -> str: temp = ['']*len(s) print(temp) # temporary list is created to hold all the characters. for i in range(len(s)): #Iterate through every letter in string 's' temp[indices[i]] = s[i] print(t...
#!/usr/bin/env python # coding: utf-8 # In[6]: import numpy as np import pandas as pd import sklearn.datasets as datasets import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression diabetes = datasets.load_diabetes() diabetes["feature_names"...
''' TIC-TAC-TOE WinterSalmon ''' from collections import namedtuple from common.equality_mixin import EqualityMixin Position = namedtuple('Position', ['row', 'col']) class Board(EqualityMixin): '''Represents TicTacToe Board''' def __init__(self, size): if size < 3: raise ValueError('siz...
def fizBizz(a): str = "" if a % 3 == 0: str += "fizz" if a % 5 == 0: str += "bizz" if str : print str for i in xrange(1, 1000): fizBizz(i)
# Determines whether the string is a palindrome def is_palindrome(str): reverse = str[::-1] return True if str == reverse else False print(is_palindrome("RooR")) print(is_palindrome("RotoR")) print(is_palindrome("RostoR"))
'''The controller in the design''' from Board import Board from Player import Player from Piece import * from ASCIIDisplay import * class Connect4Runner: def __init__(self, display): self.displayDriver = display self.board = Board() def reinitialize(self, display): self.d...
import streamlit as st import datetime as datetime dob=st.date_input('Enter DOB') def Age_Calculator(): today=datetime.datetime.now().date() age= int((today-dob).days/365.25) st.write("Your Current Age") st.success(age) if st.button('Submit'): Age_Calculator()
import numpy as np import pandas as pd import statistics import math dataset= [10,12,12, 13,12,11,14,13,15,10,10, 10, 100,12, 14,13, 12,10, 10,11,12,15,12,13,12,11,14,13,15,10, 15,12,10,14,13,15,10] dataset2=[10,8,10,8,8,4] outliers=[] def cari_outlier(data1): threshold=3 rata_1=np.mean(data1) std_1 = np.st...
# This code is used to read a file image. The image is stored as img variable. The image is then resized according to the ratio. # The ratio should be a positive number. If the ratio value less than 1, then the resized image will be smaller than its original size. import numpy as np import cv2 img = cv2.imread("fileN...
def embaralhar(s): import random import string embaralha = random.sample(s, len(s)) string = "".join(embaralha) print(string.lower()) s = str(input("Informe uma palavra:\n")) embaralhar(s)
class Pessoa: def __init__(self): self.nome = str(input("Informe o nome da pessoa:\n")) self.idade = eval(input("Informe a idade da pessoa:\n")) self.peso = eval(input("Informe o peso da pessoa:\n")) self.altura = eval(input("Informe a altura da pessoa:\n")) print("Construtor...
class ContaCorrente: def __init__(self): self.numeroConta = float(input("Informe o número da conta:\n")) self.nomedoCorrentista = str(input("Informe o nome do correntista:\n")) self.saldo = 0 print("Construtor finalizado.") def alterarNome(self): self.nomedoCorrentista = ...
demographicList = ['Age', 'Ethnicity', 'Sex'] #Writes a text file for each group of deaths for i in demographicList: with open(i + ' Deaths.csv', 'r') as text: text = text.read() #Removes werid characters at the start text = text[3:] #Creates a 2d list text = text.split('\n') for ii i...
#### By importing the random and string module in Python, #### you can generate randome passwords using this import random import string password = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10)) print password
# Sorting a numerical list! def sort_numbers(sort): numbers_list = open("numberslist.txt", "r+").read().splitlines() # Open the file, read the data, remove whitespace, convert to list length = len(numbers_list) # How many items are in the list (12 in this case) # Ascending order, bubble sort. Commen...
""" Desarrolle un programa en el que simule el lanzamiento de al menos 2 Dados y calcule cual es el numero que tiene mayor probabilidad de salir """ import random, math linea = "-"*35 result = 0 indice = 0 # indice el num con mayor probabilidad num_p = 0 # numero con mayor probabilidad p = 0 # probabilida...
# Entradas de Datos print("Escribe un numero: "); num1 = input(); num2 = input("Escribe el siguiente numero: "); # Operaciones Matematicas # Suma suma = float(num1) + float(num2); # Resta resta = float(num2) - float(num1); # Multiplicacion multiplicacion = float(num1) * float(num2); # Division division = float(num1) / ...
# Declarar un arreglo. arreglo = ['Mario',22,73.5,True,False,5]; #Accesar a los elementos de la lista. arreglo[0] = "Ubicacion0"; arreglo[1] = 7.4; arreglo[2] = 5; arreglo[3] = -25.5; arreglo[4] = "PlayStation"; arreglo[5] = True; # Sangria o indentacion. for item in arreglo: print(item); # Lista o tupla. print(...
import unittest from lists import * class TestList(unittest.TestCase): def test_sum_items_in_list(self): inputs_and_outputs = [ ([1, 2, 3, 4], 10), ([1], 1), ([0], 0), ([], 0), ([-1, 2], 1), ] for inp, expected_output in inputs_a...
def read_file(path): file = open(path, 'r') s = file.read() return s def write_to_file(path, s): file = open(path, 'w') file.write(s) file.close() def append_to_file(path, s): file = open(path, 'a') file.write(s) file.close() def numbers_and_squares(n, file_path): file = op...
import unittest from branching_and_looping import * class TestBranchingAndLooping(unittest.TestCase): def test_integers_from_start_to_end_using_range(self): inputs_and_outputs = [ ((0, 4, 1), [0, 1, 2, 3]), ((5, 8, 2), [5, 7]), ((8, 5, -1), [8, 7, 6]), ((8...
num = int(input()) previous = num - 1 next_ = num + 1 print('previous {}, next {}'.format(previous, next_))
a = int(input()) b = int(input()) for i in range(1, b + 1): if a <= i**2 and i**2 <= b: print(i**2, end = " ")
#! python3 """Walks through a folder tree and prints every file greater than or equal to a specified size in megabytes.""" import os, sys from pathlib import Path def main(args): """Walks through the current working directory and prints the absolute path of every file greater than or equal to args[1].""" ...
month, name, price = ['December', 'bread glover', 14] print(name) # uneven names and lists def drop_first_last(grades): first, *middle, last = grades # this will store the first and last element on the variable first and last and remaining on the variable list called middle avg = sum(middle)/len(middle) pr...
# -*- coding: utf-8 -*- """ Created on Sat Aug 1 20:56:31 2020 @author: SUPERNOVA2813 """ def ShellSort(array): l=len(array) grp=l//2 # this is the group within the array i=0 j=grp # Do sorting till the group is greater than 0 #compare elements between groups and swap...
a = 2 dic = {0: 'zero', 1: 'one', 2: 'two', 3: 'three'} def switch(key): print(dic.get(key)) switch(a)
import re from nltk.corpus import stopwords import pandas #------------------------------------------ #Function:cleanhtml #Params: raw_html --> raw string from which HTML tags need to be removed #Comment: Use this function to clean your string from HTML tags #------------------------------------------- def cleanhtml(...
avg__X, avg__Y = [float(num) for num in input().split(" ")] # Cost cost__X = 160 + 40*(avg__X + avg__X**2) cost__Y = 128 + 40*(avg__Y + avg__Y**2) print(round(cost__X, 3)) print(round(cost__Y, 3))
''''''''''''''''' import sys BackTracking Based Solution First we go in a particular direction and see if we can find the solution there if not we move to the next direction by backtracking at the point after which we couldn't find the solution. Analysis: N*N cells. Memory Complexity: O(N*N) we just need to store th...
""" Wikipedia Picture of the Day (POTD) download example Baseline synchronous example for comparison: downloads images and metadata in the simple but slow synchronous way i.e. one after the other. """ import sys import os import io import re import argparse import datetime import urllib.request import urllib.error im...
import sys def ask(): prompt = '>' while True: response = input(prompt) if not response: return 0 yield response def parse_args(): yield from iter(sys.argv[1:]) def fetch(producer): gen = producer() next(gen) yield from gen def main(args): if args:...
""" Accumulator generator examples http://www.paulgraham.com/accgen.html >>> f3 = foo(3) >>> f3(2) 5 >>> f3(2) 7 >>> f3(2) 9 """ class foo0: def __init__(self, n): self.n = n def __call__(self, i): self.n += i return self.n def foo0(n): def bar(i): ...
if 'raw_input' in dir(__builtins__): input = raw_input # para funcionar com Python 2 def ler_num(): num = input('+: ') try: num = float(num) except ValueError: return 0 return num def somadora(): qt_parcelas = 0 total = 0 try: while True: parcela =...
#!/usr/bin/env python from externalLib import html2text from htmlreader import * import os def convertAll(folder): """ Converts all files in the folder to text """ result = dict() reader = HtmlPageReader() for filename in os.listdir(folder): path = os.path.join(folder, filename) content = convert(path)...
# Today, Well learn about strings! *************************************************************** # A Simple String cousre = 'Python for Beginners' print(cousre) # If you want to use an apostrophe in a String; cousre = "Python for Beginner's" (# Use double-qoutes.) # If you want to use double-qoutes to high...
def cumprimenta_horario(nome, horario): if horario <12: print("Bom dia {}".format(nome)) elif horario <18: print("Boa tarde {}".format(nome)) else: print("Boa noite {}".format(nome)) def soma(num1, num2): # função com argumento e com return total = num1 + num2 return total ...
#sm-2 spaced rep algorithm(supermemo 2) ##Trial run of quiz program ## 1. Uploads vocab from shelve file ## 2. Picks 10 random vocab and puts them in an active group variable ## 3. a. Defines and ## b. Runs quiz method which is made up of question methods. ## 4. Each question's pass/fail changes the relevant s...
# -*- coding: utf-8 -*- """ Created on Thu Sep 19 21:12:05 2019 @author: Quantum Mechanics Perseverance always pays off """ class stack:#定义一个栈类 def __init__(self,lst,maxsize):#栈的形式为列表形式 self.lst=lst self.maxsize=maxsize def clear_stack(self):#栈的重置 self.lst=[] def ma...
""" Node is defined as class node: def __init__(self, data): self.data = data self.left = None self.right = None """ mylist = [] def minorder(root): if root == None: return else: minorder(root.left) mylist.append(root.data) minorder(root.right) r...
#!/usr/bin/python def factorial(n): if n==0 or n==1: return 1 else: return n*factorial(n-1) print factorial(int(raw_input().strip()))
# Enter your code here. Read input from STDIN. Print output to STDOUT class Player: def __init__(self, name, score): self.name = name self.score = score def __str__(self): return str(self.name) + " " + str(self.score) def __repr__(self): return self def comparator(x,y): ...
# -*- coding: utf-8 -*- # SI 507 - Homework 4 # Note the changed name (Lab -> Homework) # Instructions all provided in this file. # IMPORTANT: Please read ALL of the instructions for each part before starting on it. # Submit this edited code file (only) to HW 4 on Gradescope via Canvas to see test results! ## Your ...
invite = ['James', 'Mark', 'Bill'] message = ',would like to have dinner with me?' print("Hello! " + invite[0] + message) print("Hello! " + invite[1] + message) print("Hello! " + invite[2] + message) print("I invite " + str(len(invite)) + " guest for my dinner.") # print(invite[1] + "need to deel with too many thing....
filenames = ['cats.txt', 'dogs.txt'] for filename in filenames: try: with open(filename) as cat_object: contents = cat_object.read() except FileNotFoundError: pass # print("The file " + filename + " does not exist.") else: print(contents)
# phone = 'iphone' # print("Is phone == 'iphone'? I predict True.") # print(phone == 'iphone') # print("\nIs phone == 'mi'? I predict False.") # print(phone == 'mi') # food = 'meat' # print("\nIs food == 'meat'? I predict True.") # print(food == 'meat') # print("\nIs food == 'tomato'? I predict False.") # print(food...
# JackPan 2019-05-24 Top five of best travling for me spots = ['Paris', 'New York', 'Tokyo', 'Los Angeles', 'Silicon Valley'] print(spots) # print(sorted(spots,reverse = True)) # print(spots) # spots.reverse() # print(spots) # spots.reverse() # print(spots) spots.sort(reverse = True) print(spots)
likes = ['Java', 'China', 'Apple', 'Python'] # print(likes[0]) # likes[3] = 'Huawei' # likes.append('Python') # print(likes) # likes.insert(0, 'Water') # print(likes) # del likes[0] # print(likes) # print(likes.pop(3)) # apple = 'Apple' # likes.remove(apple) # print(likes) # print(apple) print(likes[3]) print(len...
# Factorial digit sum def factorial(n): '''Return n factorial.''' if n < 1: return 1 product = 1 for i in range(1, n + 1): product *= i return product def sum_digits(n): '''Sum digits of a number.''' total = 0 for digit in str(n): total += int(digit) r...
# 백준 문제(2021.6.2) # 17388번) 첫 번째 줄에 숭실대학교의 참여도, 고려대학교의 참여도, # 한양대학교의 참여도를 의미하는 세 자연수 S, K, H가 공백으로 구분되어 주어진다. (0 ≤ S, K, H ≤ 100) # 세 대학의 참여도는 모두 다르다. # 첫 번째 줄에 일처리가 잘 되고 있어 무언의 압박이 필요가 없으면 # (따옴표를 제외하고) “OK”를 출력한다. # 그 외에는 첫 번째 줄에 무언의 압박이 필요한 동아리가 속한 # 대학의 영문 이름의 첫 단어를 출력한다. 영문 이름 표기는 지문에 나온 것을 따른다. s, k, h = map(...
''' Created on Sep 25, 2014 @author: xiong_yang Description: Sequence and position generator ''' import random def gen_seq(size, pool='ACGT'): '''Generating a sequence with length of size and randomly choose character from character pool''' seq = '' for i in range(size): seq += random.sa...
import turtle MIN_LEN = 20 def tree(branchlen, t): """tree = branch with two other smaller trees""" if branchlen < MIN_LEN: return t.forward(branchlen) t.right(20) tree(branchlen-10, t) t.left(20*2) tree(branchlen-10, t) t.right(20) t.backward(branchlen) def tur(): t =...
# Exercise 12.7.1 def springcount(s: str): def count(s: str) -> dict: d = {} for ch in s: if ch != ' ': if ch in d: d[ch] = d[ch] + 1 else: d[ch] = 1 return d d = count(s) l = sorted([(k.lower(),v) f...
class Point: """Point class shows point coordinates in x, y """ def __init__(self, initX, initY): self.x = initX self.y = initY def __str__(self): return "("+str(self.x)+", "+str(self.y)+")" def getX(self): return self.x def getY(self): return self.y
""" Sofia has given you a schedule and two dates and told you she needs help planning her weekends. She has asked you to count each day of rest (Saturday and Sunday) starting from the initial date to final date. You should count the initial and final dates if they fall on a Saturday or Sunday. The dates are given as d...
""" As the input you’ll get the date of the first vacation day in the format 'YYYY-MM-DD' and the total number of vacation days. Your task is to find out which day will be the first working day after the vacation. If it’ll be Saturday or Sunday then it should be the next Monday. In this mission you have to ignore natio...
""" Your mission is to sort the list by the frequency of numbers included in it. If a few numbers have an equal frequency - they should be sorted according to their natural order. For example: [5, 2, 4, 1, 1, 1, 3] ==> [1, 1, 1, 2, 3, 4, 5] Input: Chaotic list of numbers. Output: The list of numbers in which they are...
""" We have a List of booleans. Let's check if the majority of elements are true. Some cases worth mentioning: 1) an empty list should return false; 2) if trues and falses have an equal amount, function should return false. Input: A List of booleans. Output: A Boolean. """ def is_majority(items: list) -> bool: ...
""" The main architect of the city wants to build a new highest building. You have to help him find the current highest building in the city. Input: Heights of the buildings as a 2D-array. Output: The number of the highest building and height of it as a list of integers (Important: in this task the building numbers s...
""" In the previous mission - Warriors - you've learned how to make a duel between 2 warriors happen. Great job! But let's move on to something that feels a little more epic - armies! In this mission your task is to add new classes and functions to the existing ones. The new class should be the Army and have the method...
factorial = int(input("Digite um número:")) if (factorial > 0): passo = factorial total = factorial while (passo > 1): passo = passo - 1 total = total * passo print("%d" % total) elif(factorial == 0): print("1") else: print("Erro")
def is_hometown(town): """Given a `town`, return `True` if `town` is 'San Francisco'. Arguments: town (str): A town Returns: bool: True if `town` is 'San Francisco' """ return town == 'San Francisco' def get_full_name(first_name, last_name): """Given `first_name` and `last_n...
# -*- coding: utf-8 -*- """ Created on Thu Sep 1 15:13:49 2016 @author: Administrator """ # Import modules: import tkinter as tk # Import other python class files: from sqlDatabase.MySQLDatabase import MySQLDatabase from mongoDatabase.MongoDatabase import MongoDatabase # Tkinter fonts: LARGE_FONT= ("Verdana", 12) ...
import json import os try: with open('scores', 'r') as f: players_scores = json.load(f) except IOError: #no such file, create an empty dictionary players_scores = {} #name = input("Enter new player's name: ").upper() #create a complete, new dictionary #players_scores[name] = {'GOLF':...
import heapq class Solution(object): def Autonomous_car(self, target): K = target.bit_length() + 1 barrier = 1 << K pq = [(0, target)] dist = [float('inf')] * (2 * barrier + 1) dist[target] = 0 while pq: move, targ = heapq.heappop(pq) if dist[t...
import webbrowser # Create Movie class to create multiple instances class Movie(): """ This class provides a way to store movie related information""" VALID_RATINGS = ["G", "PG", "PG-13", "R"] # Initialize and create space in memory with defining __init__. # self is the object being created. # Runn...
def count_holes(n): digits='0123456789-+' holecount=[1,0,0,0,1,0,1,0,2,1] nstr='' if (type(n)==int): if (n>=0): nstr=str(n) else: nstr=str((-1)*n) elif (type(n)==str): for i in range(len(n)): if ((0<=digits.find(n[i])<10) or ((digits.find(n[i])>=10) and (i==0))): if ((len(nstr)>0) or (0<digits....
n=int(input("Please enter n: ")) rset=set(range(1, n+1)) excluded=set() question=['No'] while (len(question)>0): question=str(input("Enter some set: ")).split() answer="" if (len(question)>1): answer=str(question[-1]) question.pop(-1) for i in range(len(question)): question[i]=int(question[i]) qset=set(quest...
from math import sqrt from data_structures import Coordinates class TestCoordinates: def test_initialization(self): coordinates = Coordinates(x=1, y=2, z=3, w=4) assert coordinates.x == 1 assert coordinates.y == 2 assert coordinates.z == 3 assert coordinates.w == 4 d...
from functools import reduce from data_structures import Coordinates class Matrix: """ Matrix data structure is used to provide operations on a two dimensional numeric data set. arguments: data: two dimensional list """ def __init__(self, data): self.data = data def at(self...
from datetime import date, timedelta def arrange_interview(candidate_id, interviewers_id): """ Get the data from the database (candidate_data & interviewers_data) :param candidate_id: candidate id sent from the UI :param interviewers_id: list of intervbiewers id sent from the UI :return: possible ...
from __future__ import division import numpy as np import sys import activation ''' The NN class relies on a parameters object theta that is a numpy structured array. In this structure, the parameters can be retrieved on string-basis. The gradients returned after backpropagating the error, have a similar stru...
import time memo = {} def fibnacci(n): if n <= 2: return 1 if n in memo: return memo[n] temp = fibnacci(n-1) + fibnacci(n-2) memo[n] = temp return temp start = time.time() for i in range(1,100): print(fibnacci(i)) end = time.time() print("The time of execution:", end-start)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat May 27 10:42:54 2017 @author: sksingh """ while True: line = input('Please enter a line: ') """ if (len(line) > 0) and (line[0] == '#'): continue """ if (line.startwith("#")): continue elif line =...
# -*- coding: utf-8 -*- """ Created on Sun Oct 13 15:35:36 2019 @author: A TULSI SHANKAR REDD """ #importing the required libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt #importing the dataset dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[ : , :-1].values Y = dataset.ilo...
def sendKap(x,s): y=x*x y=str(y) s1=y[:len(y)/2:] s2=y[len(y)/2::] s3=int(s1)+int(s2) if(s3==x): s.append(str(x)) st=input() en=input() s=[] for i in range(st,en+1): if(i>9): sendKap(i,s) elif(i==1): s.append(str(i)) elif(i==9): s.append(str(i)) if(len(s)==0): print 'INVALID RANGE' else: print ' '.jo...
votos=[0] * 5 print("De segunda a sexta diga o numero de votos de cada dia!") for x in range(5): votos[x] = int(input("{:3d} Dia! - ".format(x+1))) cont=0 for x in range(1,5): if(votos[x]>votos[cont]): cont=x if(cont==0): print("com {:2d} votos o dia campeão é Segunda Feira".format(votos[cont])) el...
def solution1(arr): answer = [] if not arr: return answer answer.append(arr[0]) for i in range(1, len(arr)): if answer[-1] != arr[i]: answer.append(arr[i]) return answer def solution2(a, b): if a > b: a, b = b, a return sum(range(a, b+1)) lst = [1,1,3...
import collections import sys class Stack: def __init__(self): self.stack = collections.deque() self.size:int = 0 def push(self, x): self.stack.append(x) self.size += 1 def pop(self) -> int: if self.size == 0: return -1 self.size -= 1 ...
# Title: MNIST Tutorial for Experts - TensorFlow # Source: https://www.tensorflow.org/versions/master/tutorials/mnist/pros/index.html # Author: Harrison Kiang, 2016 # Description: Softmax model on MNIST dataset using multilayer convolutional network # Build a Multilayer Convolutional Network using ReLu neurons # Impo...
from math import sqrt from collections import Counter def KthPrimeOfaNumber(n,k): if n%2 ==0: k-=1 if k==0: return 2 while n%2 == 0: l.append(2) n//=2 for i in range(3,int(sqrt(n))+1): if n%i ==0: k-=1 while n%i==0: ...
print("Hello World!") print(type(3)) print(type(34.12)) print(type('True')) print(type(True)) print(5 + 2 * 3) print(8 // 5 - 3) print(8 + 22 * 2 - 4) print(16- 3 / 2 + 7 - 1) print(3 ** 3 % 5) print(5 + 9 * 3 / 2 - 4) counties = ["Arapahoe","Denver","Jefferson"] my_list = [] # slicing # list[start : end] print(count...
from collections import deque import sys if __name__ == '__main__': d = deque() #create a deque class object while True: print("\t\t\t ...........DEQUE OPERATIONS.................") print("\t\t\t 1. Add element at front ") print("\t\t\t 2. Remove element from front") prin...
'''Given a list of number and a number K, return whether any two numbers from the list add up to K''' def sum(n,k): p=[] for x in range(len(n)): flag=0 s = k - n[x] z = get_index(n,x) if s in z: flag=1 p.append(s) p.append(n[x]) ...
#!/usr/bin/python """ A module that calculate if its prime number, get numbers of prime numbers according to the input. """ __author__ = "Dongwoon Jeong" __license__ = "VSU" __version__ = "0.1" __email__ = "dwjeong@valdosta.edu" __status__ = "Individual project" from typing import List def is_prime(num_a): """r...
#! /usr/bin/env python # Day 1 - Inverse Captcha import sys sys.path.append("../../..") from python_util import prints, get_input def main(): print("\n*** Part 1 ***\n") prints('1122', solve_next, 3) prints('1111', solve_next, 4) prints('1234', solve_next, 0) prints('91212129', solve_next, 9) for captcha in ge...
#! /usr/bin/env python # Day 3 - Spiral Memory import sys sys.path.append("../../..") from python_util import prints, get_input from itertools import permutations def main(): print("*** Part 1 ***") prints(1, spiral_dist, 0) prints(3, spiral_dist, 2) prints(7, spiral_dist, 2) prints(12, spiral_dist, 3) prints...
# Day 1 - Report Repair import sys def find_duo_sum(data, target): if not data or len(data) < 2: return None elif len(data) == 2: return (data[0], data[1]) if sum(data == target) else None start = 0 end = len(data) - 1 while start < end: total = data[start] + data[end] if total > target: end -= 1 el...
#! /usr/bin/env python # Day 4 - The Ideal Stocking Stuffer from hashlib import md5 def find_hash(key, ipt): return str(md5(key + str(ipt)).hexdigest()) def main(): i = 0 while not find_hash('yzbqklnj', i).startswith('00000'): i += 1 print(i) i = 0 while not find_hash('yzbqklnj', i).startswith('000000'): ...
#!/usr/bin/env python # coding: utf-8 # # Introduction to geospatial vector data in Python # In[4]: import pandas as pd import geopandas as gpd import matplotlib.pyplot as plt # ## Importing geospatial data # Geospatial data is often available from specific GIS file formats or data stores, like ESRI shapefiles...
songs = [ {"title": "happy birthday", "playcount": 4}, {"title": "AC/DC", "playcount": 2}, {"title": "Billie Jean", "playcount": 6}, {"title": "Human Touch", "playcount": 3} ] # print("===========================") # print(f'Songs --> {songs} \n') # title = list(map(lambda x: x['title'], songs)) # prin...
#※break문과 continue문은 반복문 안에서만 사용가능 #break#SyntaxError: 'break' outside loop #continue#SyntaxError: 'continue' not properly in loop i=0 while i < 1000000000000000000000000000000: i += 1 print('[i가 {}일때]'.format(i)) print('continue이전 출력문') if i %2 ==0: continue print('continue이후 출력...
''' input()함수: 표준입력(키보드)으로 부터 사용자 입력을 받는 함수.이 함수가 실행되기 전까지 Blocking상태가 된다. 즉 다음 라인의 코드가 실행이 안되고 멈춘다 입력한 값은 모두 문자열<class 'str'>로 처리된다. 방법1]한번에 하나의 데이타만 입력받기 변수 = input() 변수 = input('안내 메시지') ''' print('[input()함수]') ''' print('나이를 입력하세요?',end='') a=input() print('a의 값:{} a의 타입:{}'...
print('[튜플의 주요 메소드]') print('1.index(요소):리스트 요소의 인덱스 반환,count(요소):요소의 빈도수 반환') g='가','나','다','라','나','마','나' print('"나"의 인덱스:',g.index('나')) #print('"바"의 인덱스:',g.index('바'))#ValueError: '바' is not in list if '바' in g: print('"바"의 인덱스:', g.index('바')) print('"나"의 빈도수:',g.count('나')) print('[튜플의 산술 연산]')#...
print('[set 표현식 첫번째-{}]') print({i for i in 'HELLO'}) #{'H','E','L','O'} print('[set 표현식 두번째-set()]')#dict({})형태 print(set({i for i in 'HELLO'}))#[o] print(set(i for i in 'HELLO'))#[o] print('[set 표현식 세번째-딕셔너리]') a={'kor':90,'eng':80,'math':100} print({key for key in a})#a.keys()와 같다 print({key for key in a if ...
class TopKByHeap(object): __k=0 __topk=None __bigdata=None def __init__(self,bigdata,k): self.__bigdata = bigdata self.__k = k self.__topk = self.__bigdata[:k] """ set top k """ def setTopK(self,topk): self.__topk=topk """ left child for i inde...
""" example: 1 sorted by lambda 2 groupby """ from itertools import groupby data =[("qaz",100),("wsx",92),("edc",87),("wsx",66),("ed",56),("wsx",43)] groups = [] uniquekeys = [] data = sorted(data, key=lambda r:r[0]) for k, g in groupby(data, lambda r:r[0]): groups.append(list(g)) # Store group iterator ...
''' name: classes.py purpose: show basic python 3 classes author: joeldevel date: Augus 2020 usage: in the console: python3 classes.py ''' # a class is like a template for create many # object class book(): def __init__(self, title, author, year): self.title = title self.author =...
hash_size=10 hash_table={} for i in range (0,hash_size): hash_table[i]=[-1,-1] def insert(x): index=x%hash_size if(hash_table[index][0]==-1): hash_table[index][0]=x return elif(hash_table[index][0]%hash_size==index): ret_index=index while(hash_table[ret_index][1]!=-1): ...
from init import students from init import histudents import init import copy def custom_sort(t): # this function is used as a key so that the list is sorted by the average of each student return (t[0]+t[1]+t[2])/3 def topbyavg(): #this function list the first m students sorted by average in descending ...