blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
bfeb0c1884cf21b5255e65aed0e266edb32be70d
edenuis/Python
/Sorting Algorithms/selectionSort.py
674
3.984375
4
#Selection sort def selectionSort(numbers): for idx in range(1, len(numbers)): curr_idx = idx for sec_idx in range(idx-1, -1, -1): if numbers[curr_idx] >= numbers[sec_idx]: break numbers[curr_idx], numbers[sec_idx] = numbers[sec_idx], numbers[curr_idx] ...
ccb1ec3d8b7974b3ad05c38924c2856d2c5f01db
edenuis/Python
/Sorting Algorithms/mergeSortWithO(n)ExtraSpace.py
1,080
4.15625
4
#Merge sort from math import ceil def merge(numbers_1, numbers_2): ptr_1 = 0 ptr_2 = 0 numbers = [] while ptr_1 < len(numbers_1) and ptr_2 < len(numbers_2): if numbers_1[ptr_1] <= numbers_2[ptr_2]: numbers.append(numbers_1[ptr_1]) ptr_1 += 1 else: nu...
f223ecd346487453e555f944ebedf812602e56f8
edenuis/Python
/Code Challenges/countTriplets.py
904
4.0625
4
#Challenge: Given an array of distinct integers. The task is to count all the # triplets such that sum of two elements equals the third element. #Idea: For each number in the array of integers, count the number of pairs of # integers that adds to the number. Return the total count. def countTripletsW...
74cd66ef4db982e8e7ed720decedb37189ec452e
edenuis/Python
/Code Challenges/findKSmallestNumber.py
1,367
3.796875
4
#Challenge: Given an array and a number k where k is smaller than size of array, # we need to find the k’th smallest element in the given array. It is # given that array elements are distinct. #Idea: To modify quicksort algorithm to search for the kth smallest number def partition(numbers, start,...
e303a3be8dbb414e8135248b0390a5635957488e
edenuis/Python
/Code Challenges/maximumIndex.py
1,189
3.5
4
#Challenge: Given an array A[] of N positive integers. The task is to find the # maximum of j - i subjected to the constraint of A[i] <= A[j]. def processMin(numbers): min_set = [0]*len(numbers) curr_min = numbers[0] for idx in range(len(numbers)): if curr_min > numbers[idx]: ...
a2d089729a6ff1abfa30510b04626f932d6c6461
edenuis/Python
/Code Challenges/waysToDecodeString.py
1,387
4.09375
4
#Challenge: Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, # count the number of ways it can be decoded. For example, the # message '111' would give 3, since it could be decoded as 'aaa', # 'ka', and 'ak'. You can assume that the messages are decodable. # ...
c4013446caf02ac636bfc44731c0e401c96561bc
sebascarm/ControlFile_1.1
/componentes/logg.py
1,488
3.5
4
# -*- coding: utf-8 -*- ########################################################### ### CLASE LOGG V1.2 ### ########################################################### ### ULTIMA MODIFICACION DOCUMENTADA ### ### 20/01/2020 ...
46060a0970937408a66698f5d3cb0900af63e120
umartariq867/data-preprocessing-codes-with-datasets
/viewmissingvalues_and_sum.py
565
4
4
# 1) to view the missing values in all dataset import pandas as pd # df=pd.read_csv("data.csv") # print(df.head(50)) # 1.1) to view missing values in specific column df=pd.read_csv('house_dataset1.csv') # print(df['area'].head()) # # 2) to check missing values # # for one coloumn # print(df['area'].isnull(...
9a3dfcbf343a1a254e575978d54a989120e7f06f
Levis92/advent-of-code
/2020/07_handy_haversacks/solution.py
1,228
3.578125
4
import re from itertools import product from typing import Set, Tuple # Format data with open("data.txt") as f: data = f.readlines() """ --- Part One --- """ def get_bag_color(line: str) -> str: return " ".join(line.split()[:2]) bags = set( get_bag_color(line) for line in data if re.search("co...
1583a48a42dbe1768eb3ecb7988b6d3cd3cbb7e6
Levis92/advent-of-code
/2019/04_secure_containers/solution.py
1,264
3.5625
4
from collections import Counter PUZZLE_INPUT = "248345-746315" low_end, high_end = [int(number) for number in PUZZLE_INPUT.split("-")] """ --- Part one --- """ def get_digit(number, n): return number // 10 ** n % 10 def two_adjacent(digits): prev = None for digit in digits: if prev is not No...
c47ca14b6acc07719b5b371657ff32d6d69e4a85
GoldeneyesII/BrutePy
/brute.py
1,668
3.734375
4
#Python script to generate brute-forced word list #Successfully appends list to file #Successfully reads last line of file (without reading whole file) #Need to create a "starting point" for generate #Starting point includes how many chars are in word #Starting point includes ord(char) for each char in word #Ge...
5e5616cf598e0f6d54efae751cea864e525e4d21
eugabrielpereira/Atividades_em_Python
/02.py
97
3.78125
4
a=input("Qual o seu nome?") print("Seja muito bem-vindo {}, é um prazer te conhecer!".format(a))
361b148b6c738a77429192b310c1cd6094bb1465
eugabrielpereira/Atividades_em_Python
/24.py
378
3.859375
4
print("iremos calcular a sua corrida") print("Nossas tarifas estão atualizadas para R$0,50 em viagens de até 200km e superiores R$0,45") a=float(input("Digite quantos KM será a viajem:")) curta=a*0.50 longa=a*0.45 if a<200: print("A sua viagem de {:.2f} km custará R${:.2f}".format(a,curta)) else: print("A sua v...
9703256d0914b9527dcffa421a352c5e78680675
eugabrielpereira/Atividades_em_Python
/03.py
209
4.09375
4
a=input("Digite o seu salário:") b=input("Qual o seu nome?") print("Nome do funcionário: {}".format(b)) print("O salário é de: R${}".format(a)) print("O funcionário {} tem o salário de R${}".format(b,a))
7e72c022732d0cbb2c7e7d7efc8ce63c0dea835e
IanMadlenya/StockSentimentNN
/snpquotes.py
1,670
3.515625
4
import urllib import csv import time def get_historical_prices(symbol, start_date, end_date): """ Get historical prices for the given ticker symbol. Date format is 'YYYYMMDD' Returns a nested list. """ url = 'http://ichart.yahoo.com/table.csv?s=%s&' % symbol + \ 'd=%s&' % str(int(en...
2908f21ab30d83fb7de32c3094236b5db6c98127
seungahkim1024/tf_day1
/bmi_calc/__init__.py
283
3.703125
4
from bmi_calc.bmi import Bmi def main(): bmi = Bmi((input("이름 ")) , int(input("키 ")) , int(input("몸무게 "))) print("{}님의 BMI는 {}" .format(bmi.name , bmi.bmi())) if __name__ == '__main__': main()
7bc45e8918ca3c516d66e96f58ced02da3485eb0
KarenaBradley/cti110
/P2HW2_ListSets_BradleyKarena.py
391
3.734375
4
# CTI-110 # P2HW2 - List and Sets # Karena Bradley # 6-19-2021 input_string = input('Enter a series of 10 numbers: ') print("\n") num_list = input_string.split() print('List: ', num_list) for i in range(len(num_list)): num_list[i] = int(num_list[i]) print('Lowest number = ', min(num_list)) p...
12430663209511aa51c211636665cebced442d9d
criptonauta/weio
/sandbox/hashableItem/test.py
595
3.796875
4
class Pin(object): def __init__(self, pin, mode): self.pin = pin self.mode = mode def __repr__(self): return "Pin(%s, %s)" % (self.pin, self.mode) def __eq__(self, other): if isinstance(other, Pin): # Check if pin is the same, mode is not relevant retu...
4b36974153e396dfa4e4034c026a148aa628661b
coding-ax/pyproject
/small/make_pizza.py
134
3.578125
4
def make_pizza(size,*toppings): print(str(size)+" size pizza we need") for topping in toppings: print("- "+topping)
c45fb28d95d1ac6ca1cc5ac3c6ebf86cf4a039fd
durcak/v122
/cv3/simple_img.py
750
3.734375
4
from Turtle import Turtle from math import sqrt, ceil, sin,tan,cos,pi def squares(max_levels = 15): t = Turtle('squares') d = 300 for i in range(max_levels): for i in range(4): t.forward(d) t.right(90) t.forward(d/4) t.right(90/5) d = sqrt((d/4)**2 + (d - d/4)**2) t.save() def triang...
fa488171d4154eeed7bb517a0ae8b4a73b7c6479
durcak/v122
/cv3/kvet.py
376
3.859375
4
from Turtle import Turtle import math turtle = Turtle('kvet') def step(dist, depth): if depth == 0: return turtle.forward(dist) turtle.left(45) step(2*dist//3, depth - 1) turtle.right(90) step(2*dist//3, depth - 1) turtle.left(45) turtle.pen_up() turtle.back(dist) turtle.pe...
64fe2ed64c6fe5c801e88f8c1e266538f7d51d40
brodieberger/Control-Statements
/(H) Selection statement that breaks loops.py
345
4.25
4
x = input("Enter string: ") #prompts the user to enter a string y = input("Enter letter to break: ") #Letter that will break the loop for letter in x: if letter == y: break print ('Current Letter:', letter) #prints the string letter by letter until it reaches the letter that breaks the loop. input ...
cb78a9762ed272928f68dfbf1a022da7535eeaea
AngelFA04/LibroProbabilidad
/C7_diamante_en_cuadro.py
399
3.515625
4
import random def punto_en_cuadro(): return (random.random(), random.random()) def esta_en_diamante(x,y): return x+y < 1 and x-y < 1 and -x+y < 1 and -x-y < 1 simulaciones = 100000 dentro = 0 for simulacion in range(simulaciones): (x,y) = punto_en_cuadro() if esta_en_diamante(x,y): dentro +=...
65a689f1de3ff3c13803f7f3bc76a8ae95f36df5
AngelFA04/LibroProbabilidad
/A1_integer_simplex.py
253
3.5
4
import random def enteros_aleatorios_de_suma(suma, n): U = list(range(suma+n-1)) L = random.sample(U,n-1) L.append(-1) L.append(suma+n-1) L.sort() return [L[i+1]-L[i]-1 for i in range(n)] print(enteros_aleatorios_de_suma(5,3))
c4767200a34ff1962e7e56f0d4e8a90501f253dc
songyachun/Python-Workbook
/Data Structures and Algorithms/Chaper 7 链表/双向链表实现双端队列Deque.py
1,479
3.84375
4
""" 使用哨兵时,实现方法的关键是要记住双端队列的第一个元素并不存储在头节点,而是存储在头节点后的第一个节点。同样,尾节点之前的一个节点中存储的是双端队列的最后一个元素 """ from 双向链表基本类 import _DoublyLinkedBase class LinkedDeque(_DoublyLinkedBase): """ Double-ended queue implementation based on a doubly linked list """ def first(self): """ Return (but do not remove) the element at...
3cb15536e39ee3bde14f82b9b0a1f3b199c20949
songyachun/Python-Workbook
/Data Structures and Algorithms/Chaper 5 基于数组的序列/Python列表类增添操作的摊销花费.py
510
3.625
4
from time import time def comptuter_average(n): """ Perform n appends to an empty list and return average time elaosed. """ data = [] start = time() for k in range(n): data.append(None) end = time() return (end-start)/n if __name__ == "__main__": print(comptuter_average(100)) ...
cd5c90946a11fadeeaff9c315b133790e32a742b
benoitputzeys/Udemy
/RNN/RNN-Prediciton-of-Google-Stock-Price.py
8,455
4.15625
4
# Recurrent Neural Network # Part 1 - Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the training set dataset_train = pd.read_csv('Google_Stock_Price_Train.csv') # Convert the dataframe to np.array. # iloc method is to get the right i...
0af5be1b677b7d0734e0bc071f03f74007bb960a
Chil625/FlaskPractice
/lec1/if_statements.py
1,039
4.15625
4
# should_continue = True # if should_continue == True: # print("Hello") # # people_we_know = ["John", "Anna", "Mary"] # person = input("Enter the person you know: ") # # if person in people_we_know: # print("You know {}!".format(person)) # else: # print("You don't know {}!".format(person)) def who_do_you...
26aac394d6c631567996cc101c87ae2831a887f2
AlimKhalilev/python_tasks
/laba5.py
511
3.75
4
def getNumber01(num): while type: getNumber = input('Введите число ' + num + ': ') try: getTempNumber = float(getNumber) except ValueError: print('"' + getNumber + '"' + ' - не является числом') else: break return float(getNumber) x0 = getNum...
b3e805e5fc1d30f9ef18c6a19d7c9ebe8aa12168
AlimKhalilev/python_tasks
/laba6.py
1,090
3.921875
4
import math def getNumber01(num): while type: getNumber = input('Введите число ' + num + ': ') try: getTempNumber = float(getNumber) except ValueError: print('"' + getNumber + '"' + ' - не является числом') else: break return float(getNumber) ...
4ea420af19f4c420528a242fb9f5a5c1aa0468a6
Shawonskh/Robotics
/lab10/TSP.py
2,974
3.609375
4
import itertools import math class TSP: def __init__(self): self.points = [] # list of point IDs on path self.distances = {} # map of distances between each point pair self.paths = {} self.startID = 0 # start point ID # Register a point that needs to be visited # pointID...
09e6f8519cfbc96df88224c90e50221c32430290
Shawonskh/Robotics
/lab10/Drive.py
2,678
3.8125
4
from math import sqrt, degrees, atan2 class Drive: # The Drive object needs to know the path that it should follow # path - list of Node: shortest path return by the TSP library def __init__(self, path): # Constructor self.path = path self.next_drive_index = 0 self.current_point =...
a223654abed4a54be995804cb671597b7efb987a
Wathone61/JanKenPon
/jkp.py
3,884
3.65625
4
''' ==================================== JANKENPON (Rock, Paper, Scissors) ==================================== Ricardo Reis 2019 03/03/2019 - 16/03/2019 [DD/MM/YYYY] Python Version 3.7.0 Version 1.0 JANKENPON ''' from random import randint user_wins = 0 pc_wins = 0 draw = 0 debug_mode = 0 # lets the ...
b36503282926d73cabe8f8d0a9fa312484b25f4f
nhforman/MicromouseSimulator
/algorithm/search.py
3,338
3.859375
4
from stack import Stack from robot_wrapper import Robot, Direction from maze import Maze, Neighbors, Square class Move: def __init__(self, current_x, current_y, direction): self.x = current_x + (direction % 2) * (direction - 2) self.y = current_y + ((direction % 2)-1) * (direction - 1) self.parent_x = current_...
d1c62ceac596e278eb65387ade721d625167df60
mateusfg7/textAnalysis
/utils/removeStopwords.py
278
4
4
from typing import List def removeStopwords(text: str, stopwords: List[str]) -> str: ''' Removes the chosen stopwords in the text then return the text without stopwords. ''' for stopword in stopwords: text = text.replace(stopword, ' ') return text
465c4d819e72387ecb9ce868ad9fa233fc5250be
marinelavlad/Homework-BankAppATMApp
/atmpackage/modificare_pin.py
930
3.5
4
import json def new_pin(nr_card): noul_pin = input("Introdu noul cod PIN format din 4 cifre:\n> ") verificare_noul_pin = input("Reintrodu noul cod PIN pentru verificare:\n> ") ok = 0 if len(noul_pin) == 4: if noul_pin == verificare_noul_pin: ok = 1 else: print("C...
6fa53134bc2f92250e9648190daa0fc33b79a9be
SakibPatwary/Artificial_Intelligence
/LabCodeTask.py
1,232
3.609375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: graph={ 'S':{'A':5,'B':2,'C':4}, 'A':{'D':9,'E':4}, 'B':{'G':6}, 'C':{'F':2}, 'D':{'H':7}, 'E':{'G':6}, 'F':{'G':1}, 'G':{}, 'H':{} } from queue import PriorityQueue def Uniform_Cos...
d87eca62ff8d9d00c4f24dad0bee445d8adbe6e7
frhrdr/dp-merf
/code_tab/feature.py
4,338
3.515625
4
"""Module containing classes for extracting/constructing features from data""" __author__ = 'wittawat' from abc import ABCMeta, abstractmethod import numpy as np import scipy.stats as stats import util as util class FeatureMap(object): """Abstract class for a feature map function""" __metaclass__ = ABCMeta ...
1b4696265119f817c2d4fb1f02c5837acdde39e6
zhouzhou-May/zym_practice
/common/practice.py
4,687
3.609375
4
"""1 2 3 4组成的所有三位数,且不出现重复 for i in range(1, 5): for j in range(1, 5): for k in range(1, 5): if(i != j) & (i != k) & (j != k): print('%d' % i, '%d' % j, '%d' % k) """ # class Person(): # # def __init__(self, name): # self.first_name = name # # @property # def ...
ff4528060dd76013f6103222b696583d0b1bb72f
bauhuasbadguy/SHA-2-algorithm
/SHA-2.py
7,939
4.03125
4
# -*- coding: cp1252 -*- #SHA-2 #My SHA-2-256, this is for educational purposes so it'll be slow. #If you want to do real encryption go to a proper programmer. #This stuff would run faster on a GPU because it's mostly #bitwise operations #This is the hashing algoritm used by Bitcoin as well as most of #the internet #...
3347f2b53490020eaf895611c5d0f07668f55ca2
Link-lin/test
/chap11/file.py
127
3.953125
4
#!/usr/bin/env python3 f = open('somefile.txt') file_as_list = f.readlines() for line in file_as_list: print(line, end='')
130717e9630867ed4a34981cab561da646cff63b
klimova00/Python_4_les
/4_les/4_les_6_ex.py
669
3.703125
4
from itertools import count from itertools import cycle print("итератор, генерирующий целые числа, начиная с указанного. Для выхода введите EOF. ") for i in count(int(input("Enter start number: "))): print(i) end = input() if end == "EOF": break print("итератор, повторяющий элементы некоторого спис...
1d3a7ebb3162bc2ff8c1d356e1c1e3a5550daadd
Sameeraapplines/oct-1-quiz
/pr1.py
394
4.03125
4
#frequency count text = input("enter text\n") my_dict = {} word_list = text.split() for words in word_list: if (words[-1] == '.' or words[-1] == ','): words = words[0:len(words) - 1] if words in my_dict: my_dict[words] += 1 else: my_dict.update({words: 1}) #Print the dictionary for ...
688929fc57b6c1a90174e693de45982f09e8c9c4
coreyrwright/mountaineersapp
/automated_climbers.py
2,102
4.0625
4
import time import math import random number_of_players = "" number_of_ACs = "" number_of_mountain_sides = "" def print_pause(message_to_print): print(message_to_print) time.sleep(1) def valid_text_input(input_description, valid_responses): while True: response = input(input_description).lower...
343551bf103a2dbe43606aec20cd2c00e9216d26
anaf007/my_flask_extendsions
/my_flask_extendsions/pystack.py
1,702
3.921875
4
#coding=utf-8 """ 创建一个简单的堆栈结构 """ class PyStack: def __init__(self,size=20): self.stack = [] #堆栈列表 self.size = size #堆栈大小 self.top = -1 #栈顶位置 def setSize(self,size): self.size = size def push(self,element): if self.isFull(): raise StackExc...
684a7eac2362be4e95bedc78ae9fb7ba037dc4b4
kaktakdavottak/hwfile
/hwfile.py
1,588
3.59375
4
def f_read(): cook_book_dict = {} with open('recipelist.txt') as f: for line in f: dish = line.strip() ingredients_number = f.readline().strip() n = int(ingredients_number) ingredient_dict_list = [] for lines in range(n): ingr...
3dfabfb50f3421602283acfc75fb1401f0f2f8aa
ikramjaujate/batailleNavale
/ocean.py
2,431
3.796875
4
class Ocean: def __init__(self, hauteur : int): """ Utilisation : mon_ocean = Ocean(hauteur) :param hauteur: la hauteur de la grille :type hauteur: int PRE : - POST : Assigne la valeur hauteur introduite comme paramettre à une autre variable """ self...
2fd02e4ef529c04cb315456e58c2533f94ed4df6
austBrink/Tutoring
/python/Maria/targetGame.py
1,608
4.375
4
# Hit the Target Game # 02/11/23 # Maria Harrison import turtle # named constants SCREEN_WIDTH = 600 SCREEN_HEIGHT = 600 TARGET_LLEFT_X = 100 TARGET_LLEFT_Y = 250 TARGET_WIDTH = 25 FORCE_FACTOR = 30 PROJECTILE_SPEED = 1 NORTH = 90 SOUTH = 270 EAST = 0 WEST = 180 # Setup the window turtle.setup(SCREEN_WIDTH, SCREEN_HEIG...
ed767807eae30530f1d4e121217585aff3bcea75
austBrink/Tutoring
/python/Maria/makedb.py
2,370
4.34375
4
import sqlite3 def main(): # Connect to the database. conn = sqlite3.connect('cities.db') # Get a database cursor. cur = conn.cursor() # Add the Cities table. add_cities_table(cur) # Add rows to the Cities table. add_cities(cur) # Commit the changes. ...
7626635b10874cd45ef572540d1347eeff90a00e
austBrink/Tutoring
/python/Maria/databasereader.py
1,258
4.40625
4
import sqlite3 conn = sqlite3.connect('cities.db') # city id, city name, population namesByPop = conn.execute(''' SELECT CityName FROM Cities ORDER BY Population ''') for row in namesByPop: print ("ID = ", row[0]) print ("CITY NAME = ", row[1]) print ("POPULATION = ", row[2] ) namesByPopDesc = conn...
bf639aca06615e7a8d84d9322024c17873504c00
austBrink/Tutoring
/python/Sanmi/averageRainfall.py
1,362
4.5
4
# Write a program that uses ( nested loops ) to collect data and calculate the average rainfall over a period of two years. The outer loop will iterate once for each year. The inner loop will iterate twelve times, once for each month. Each iteration of the inner loop will ask the user for the inches of rainfall for tha...
dc05a23277b63899ceaf790bbaa3b663e32d4aa0
austBrink/Tutoring
/python/Quinton/intro.py
368
3.921875
4
#output. print('Hello World') # variables / types # 1 is a number # 'hello world! 321' is a string # variable myFirstNumber = 9 # blocks. if(myFirstNumber == 9): print('that variable musta been 9') # input print('a number') num1 = int(input()) print('enter another number') num2 = int(input()) print("...
2431602246774b0927d350f4bad28aacd33b3f2a
austBrink/Tutoring
/python/studentsBummingRides.py
501
3.984375
4
print("please enter a number for available drivers/parents/gaurdians") parents = int(input()) students = 24 studentsPerParent = 4 # we want to know how many students will NOT have a ride. Well, how many WILL? studentsWithRide = parents * studentsPerParent studentsWithNoRide = students - studentsWithRide print(...
c25780c144bbff40242092fbbe961a3b5e72c8e4
roshan1966/ParsingTextandHTML
/count_tags.py
862
4.125
4
# Ask the user for file name filename = input("Enter the name of a HTML File: ") def analyze_file(filename): try: with open (filename, "r", encoding="utf8") as txt_file: file_contents = txt_file.read() except FileNotFoundError: print ("Sorry, the file named '" + filename + "...
b17bcdf574f4db1a22c9bf5019342138bcf7e9ce
udaybhaskar8/git-project
/variables and data types/ex9.py
254
3.796875
4
str1 = 'abcefghxyzThis,is,the,target,string xyzlkdjf' idx1 = str1.find( 'xyz' ) idx2 = str1.find('xyz', idx1+1) str1 = str1[idx1+3:idx2].replace(',' ,'|') str1 = str1. strip() print(str1)
374c16f971fc2238848a91d94d43293c592e6f03
udaybhaskar8/git-project
/functions/ex4.py
322
4.125
4
import math # Calculate the square root of 16 and stores it in the variable a a =math.sqrt(16) # Calculate 3 to the power of 5 and stores it in the variable b b = 3**5 b=math.pow(3, 5) # Calculate area of circle with radius = 3.0 by making use of the math.pi constant and store it in the variable c c = math.pi * (3**2...
4f65653969484ebdead97ccd7ea64fba140194e7
hellokena/BOJ
/문자열/1181_단어 정렬.py
327
3.625
4
import sys n = int(sys.stdin.readline().rstrip()) array = [] for i in range(n): word = sys.stdin.readline().rstrip() if word not in array: # 같은 것 제외 array.append(word) array.sort() # 알파벳 순으로 1차 정렬 array.sort(key=lambda x: len(x)) # 길이로 1차 정렬 for i in array: print(i)
4e6097699dc103f3c907f12638330486be45fd8f
hellokena/BOJ
/입출력과 사칙연산/2558_곱셈.py
268
3.796875
4
a = int(input()) b = input() print(a*int(b[2])) print(a*int(b[1])) print(a*int(b[0])) print(a*int(b)) ''' int first_digit = first_num*(second_num/100); int second_digit = first_num*(second_num/10%10); int third_digit = first_num*(second_num%10); '''
7e1fccc4b31ff0a0682e424d1881eec092fd320e
hellokena/BOJ
/for문/8393_합.py
89
3.671875
4
num = int(input()) ans = 0 for i in range(1, num+1): ans = ans + i print(ans)
435d4def1fc73f5623c846e5034998354f752dd7
hillarychristines/71180386_GRUP__A
/konversi_paswword.py
547
3.625
4
file = open("password.txt",'w+') password = input("Masukkan Angka : ") print("1. Hexadecimal") print("2. Oktal") print("3. Biner") print("Mau diubah menjadi apa : ") choice = int(input("Masukkan Pilihan : ")) if choice == 1 : konversi = int(password, 16) print("Sudah berhasil") elif choice == 2 : ...
60921fee9d065819ebb62b5a3cdf77ca7047f9ab
ace6807/spec-data-validation-pattern
/spec/base.py
1,064
3.5
4
from abc import abstractmethod from dataclasses import dataclass from typing import Any class Spec: @abstractmethod def passes(self, candidate: Any) -> bool: raise NotImplementedError() def __call__(self, candidate: Any) -> bool: return self.passes(candidate) def __and__(self, other:...
875ba0b6d7a5aa863de6e8fdc45901fa2108cc6d
tlkoo1/Lok-Koo.visualisation
/basicDrawing.py
1,184
3.703125
4
from graphics import * import random #random.display.init() # Read in and print out the data in the data file datafile = open("data.txt",'r') #for line in datafile: print(line) # Do some simple drawing window = GraphWin("Visualisation", 600, 600) i=0 for line in datafile: line = Line(Point(300,i*5),Point(300,i*...
6b740dc927a08078b70eda526cfbefb1168c4465
Rochakdh/python-assignemnt-3
/2.insertion.py
371
4.0625
4
def insertion(ip_list): for i in range(1,len(ip_list)): for j in range(i-1,-1,-1): if ip_list[j]>ip_list[i]: ip_list[j],ip_list[j+1] = ip_list[j+1],ip_list[j] #or # if ip_list[0]>ip_list[1]: # ip_list[0],ip_list[1]=ip_list[1],ip_list[0] return ip_list if __name__ == ...
db74516576a42cb00f2f6f10acee4472b69f1f85
ka10ryu1/activation_func
/func.py
848
3.59375
4
#!/usr/bin/env python3 # -*-coding: utf-8 -*- # help = '便利機能' # import os def argsPrint(p, bar=30): """ argparseの parse_args() で生成されたオブジェクトを入力すると、 integersとaccumulateを自動で取得して表示する [in] p: parse_args()で生成されたオブジェクト [in] bar: 区切りのハイフンの数 """ print('-' * bar) args = [(i, getattr(p, i)) for...
0bbf5a52c8968514acdee8b5ae3ec415a4c62b62
PiaNgg/Trabajo06_Validadores
/condicional_multiple_03.py
589
3.875
4
import os # CALCULO DEL AREA DEL CIRCULO radio,pi=0.0,0.0 # ASIGNACION DE VALORES radio=float(os.sys.argv[1]) pi=float(os.sys.argv[2]) # CALCULO area_del_circulo=str(pi*(radio**2)) # CONDICION DOBLE if area_del_circulo<str(0): print("ERROR,EL AREA DEL CIRCULO NO PUEDE SER NEGATIVA") elif area_del_c...
e5df8963e43fab131222b8196a40dfb51ba2a0cb
PiaNgg/Trabajo06_Validadores
/condicional_doble_14.py
948
3.5625
4
# BOLETA DE VENTA DE UNA PANADERIA import os tipo_pan_1 =(os.sys.argv[1]) tipo_de_pan_2 = (os.sys.argv[2]) P_U_1 = float(os.sys.argv[3]) P_U_2 = float(os.sys.argv[4]) unidades_1 = int (os.sys.argv[5]) unidades_2 = int (os.sys.argv[6]) TOTAL = P_U_1 * unidades_1 + P_U_2 * unidades_2 print ( " #######...
337a147afaca31280d9b6abe2f7e7404425a0ee2
laychow/Self-study
/Python Coding/python_work/pi_reader.py
238
3.78125
4
with open('pi_dig.txt')as file_object: contents=file_object.readlines() pi='' print(contents) for content in contents: pi+=content.strip() birthday=input("Enter your birthday:") if birthday in pi: print("ture") else: print("false")
5515c849ac9bf56205cee43c73cf6f98e4c6257d
laychow/Self-study
/Python Coding/python_work/Emplyee_class.py
313
3.765625
4
class Employee(): def _init_(self,first,last,salary): self.first_name=first self.last_name=last self.salary=salary def give_raise(self,increase=5000): self.salary+=increase def Information_display(self): full_name=first_name+' '+last_name print("\nName: "+full_name.title()+" "+salary);
027df59cd170cb825d8e00204225cac1d51a8c4e
QWJ77/Python
/StudyPython/Python分支循环-综合案例水仙花数.py
663
3.75
4
# 水仙花数,十位三次方*各位三次方*百位三次方=它本身 # 准备一个3位数 ''' 让用户输入数据 判断数据有效性(保证数值是3位数) ''' while True: num=input("请输入3位数值:") num=int(num) if not 100<=num<=999: print("你输入的数据无效,直接退出程序") exit() # 判断是否是水仙花数 ''' 分解百位、十位、各位 ''' bai=num//100 shi=num % 100//10 ge=num % 100 % 10 res...
1af9b2bc038c3da8103217d322477227365253ef
QWJ77/Python
/StudyPython/Python循环-for与else连用.py
81
3.609375
4
name="我爱中国" for c in name: print(c) else: print("遍历结束")
7da3502b744ac270d60ed49a9f49a0751466cfcc
QWJ77/Python
/StudyPython/Python字典-定义.py
1,439
3.96875
4
# 无序的,可变的键值对集合 ''' 方式一{key1:value1,key2:value2,...} ''' # person={"name":"sz","age":18} # # 注:不能通过索引去取 # print(person["name"]) # print(person["age"]) ''' 方式二 静态方法,生成字典类和对象都可以进行调用 dict.fromkeys(seq,value=None),一般不用对象去调用,seq可以是字符串,列表,元祖等序列 ''' # d=dict.fromkeys("abc") #{'a': None, 'b': None, 'c': None} # print(d) # f=d...
8cbf7ced0288a54a95a02aef4a1e0fe6074cb936
QWJ77/Python
/StudyPython/Python循环-for.py
160
3.765625
4
# 主要场景就是遍历一个集合 notice="方兜是只猪" for c in notice: print(c) pet=["小花","小黑","小红"] for name in pet: print(name)
2bde5f62a21b8294f07c59180bd54b7035bf0e15
QWJ77/Python
/StudyPython/test1计算体脂率-优化案例.py
1,479
3.9375
4
''' 输入: 身高、体重、年龄、性别 处理数据: 1、计算体脂率 BMI=体重(kg)/(身高*身高)(米) 体脂率=1.2*BMI+0.23*年龄-5.4-10.8*性别(男:1 女:0) 2、判定是否在正常范围内 正常范围:男15%~18%,女25%~28% 输出: 告诉用户是否正常 ''' height=float(input("请输入身高(m):")) weight=float(input("请输入体重(kg):")) age=int(input("请输入年龄:")) sex=int(input("请输入性别:(男:1 女:0)")) # 容错处理 # 优先级not->and->or # if 0<height<3 ...
7a0335526df3d77c0f105105b31569a443565411
QWJ77/Python
/StudyPython/Python数值-随机数.py
473
4
4
# 都隶属于random import random #random() [0,1)范围内的随机小数 print(random.random()) # choice(seq)从 一个序列中随机玄炽一个数值 seq=[1,5,6,7,9] print(random.choice(seq)) # uniform(x,y) [x,y]范围内的随机小数 print(random.uniform(1,9)) # randomint(x,y) [x,y]范围内的随机整数 print(random.randint(1,3)) # randrange(start,stop=None,step=1) 返回给定区间的随机整数[start,stop),...
0536bf4d5ab562112a5971e9b517da0513f460dc
QWJ77/Python
/StudyPython/Python-函数的值传递和引用传递.py
950
4.1875
4
''' 值传递:传递过来的是一个数据的副本,修改副本对原件没有任何影响 引用传递:传递过来的是一个变量的地址,通过地址可以操作同一份文件 注:在Python中,只有引用传递 但是,如果数据类型是可变类型,则可以改变原件 如果数据类型是不可变类型,则不可以改变原件 可变数据类型:列表list和字典dict; 不可变数据类型:整型int、浮点型float、字符串型string和元组tuple。 ''' # 如果数据类型是不可变类型,则不可以改变原件 # def change(num): # print(id(num)) # num=666 # print(id(num)) # # b=10 # print(id...
ec3c637f34938d142797ed51f4184c807455335f
QWJ77/Python
/StudyPython/Python列表-常用操作-增加.py
894
4.34375
4
''' append 往列表里追加一个新元素,只追加一个元素 注意:会直接修改原列表!!! ''' # nums=[1,2,3,4,5] # print(nums) # print(nums.append(5)) # print(nums) ''' insert(index,object) 插入到index的前面 它会改变列表本身!!! ''' # nums=[1,2,3,4,5] # print(nums) # print(nums.insert(0,5)) # print(nums) ''' extend 往列表中。扩展另一个可迭代序列,把可迭代元素分解成每一个元素添加到列表 它会改变列表本身!!! ''' nums=[1...
643933bf7cc076369534118302805ff2a17aea47
tjbeatty/sde_study_club
/warehouse_traverse.py
2,084
3.671875
4
warehouse_floor = [ [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0], ] def neighbors(coord): [i, j] = coord # Potential neighbors are above, below, left, and right of coordinate neighbor_list = [[i, j + 1], [i, j - 1], [i + 1, j], [i - 1, j]] return neighbor_list # Check if...
890ae7b46c38ee2c77ea8b7d574f5998573efb34
Tech-nransom/dataStructuresAndAlgorithms_Python
/bubbleSort.py
460
4.4375
4
def bubbleSort(array,ascending=True): for i in range(len(array)): for j in range(i,len(array)): if ascending: if array[i] > array[j]: array[i],array[j] = array[j],array[i] else: if array[i] < array[j]: array[i],array[j] = array[j],array[i] return array # 9 2 5 1 3 7 if __name__ == '__m...
9affcfc38a322081ef4afeb658aa97ec03f871ab
mckennec2014/cti110
/P3HW1_ColorMix_ChristianMcKenney.py
975
4.28125
4
# CTI-110 # P3HW1 - Color Mixer # Christian McKenney # 3/17/2020 #Step-1 Enter the first primary color #Step-2 Check if it's valid #Step-3 Enter the second primary color #Step-4 Check if it's valid #Step-5 Check for combinations of colors and display that color # Get user input color1 = input('Enter t...
7008005de70aadea1bebd51d8a068272c7f7b6af
mckennec2014/cti110
/P5HW2_MathQuiz _ChristianMcKenney.py
2,012
4.375
4
# This program calculates addition and subtraction with random numbers # 4/30/2020 # CTI-110 P5HW2 - Math Quiz # Christian McKenney #Step-1 Define the main and initialize the loop variable #Step-2 Ask the user to enter a number from the menu #Step-3 If the user enters the number 1, add the random numbers and #...
a7c58747a8ba847e7478321911940b6a67340869
ismlambo/First_Semester_projects
/submission_005-toy-robot-2/robot.py
12,627
4.125
4
import re def get_robotName(): """The user is asked to provide an alias for the robot that will be used throughout the run of the programme""" robotName = input("What do you want to name your robot? ") print(robotName + ": ",end="") print("Hello kiddo!") return robotName def robot_await_comm...
965525103ec49400ce96e795f58a183951a75de3
Dom26/8-queens
/popNode.py
6,079
3.609375
4
# popNode file # This file contains the node that holds an array of # boardNodes, or more accurately a population of boardNodes # CS 441 assignment 2 # Instructor: Rhoades # Author: Dominique D. Moore import boardNode # population = # of board states # boards = array of board states (or boardNodes) # fitne...
b8fb37f1b04a1526b20cf2c55a97e9937d7eab22
Garthof/scriptlets
/sampling/random/list_sampling.py
3,710
3.71875
4
import random def sample_population(event_list): """ Returns a list containing one tuple (sample, label) for each of the lists in event_list. The samples are selected so the proportion of associated labels in the final result respects the description in weighted_labels. """ selected_events ...
7e3ff4cbf422f91773d66991a05720718ec42bd7
cs112/cs112.github.io
/recitation/rec8.py
1,585
4.1875
4
""" IMPORTANT: Before you start this problem, make sure you fully understand the wordSearch solution given in the course note. Now solve this problem: wordSearchWithIntegerWildCards Here we will modify wordSearch so that we can include positive integers in the board, like so (see board[1][1]): board = [ [ 'p'...
63d2eda6cbc8cbfc8c992828adb506ffd7f5a075
cs112/cs112.github.io
/challenges/challenge_1.py
759
4.15625
4
################################################################################ # Challenge 1: largestDigit # Find the largest digit in an integer ################################################################################ def largestDigit(n): n = abs(n) answer = 0 check =0 while n >0: ch...
703e9338c35faf5777d3c55c0dfa16b2eb39a1d7
cs112/cs112.github.io
/recitation/rec5.py
5,692
3.78125
4
############################################################################## # String CT [5 mins] ############################################################################## def ct1(s, t): result = "" for c in s: if (c.upper() not in "NO!!!"): i = t.find(c) if (result != ...
bf8a5b7c08d85ce24ffbd20c4c67d74d316dbbcf
adwaraka/algorithms
/rotation_detection.py
887
3.859375
4
#to detect a rotation inside an otherwise sorted array def rotation_search(arr, low, high): if (low < high): if arr[low] < arr[high]: mid = (low + high)//2 if arr[low] < arr[mid]: return rotation_search(arr, mid, high) elif arr[mid] < arr[high]: ...
e086c396cc206db98c245ce06629910ca9415422
ymfa/relue
/p1.py
144
3.703125
4
total = 0 for number in [3, 5]: n = number while n < 1000: if number != 5 or n % 15 != 0: total += n n += number print(total)
a54c2b076076610827879f1dacfd549021ab6c9b
BaoziSwifter/MyPythonLeetCode
/pythonLeetcode/617-合并二叉树.py
2,017
3.53125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/9/4 16:11 # @Author : Beliefei # @File : 合并二叉树.py # @Software: PyCharm """ 给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。 你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。 示例 1: 输入: Tree 1 Tree 2 ...
ec917d08cd3a3ea21e48f7f307671a9c0e9e952e
BaoziSwifter/MyPythonLeetCode
/pythonLeetcode/67-二进制求和.py
792
3.875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 给定两个二进制字符串,返回他们的和(用二进制表示)。 输入为非空字符串且只包含数字 1 和 0。 示例 1: 输入: a = "11", b = "1" 输出: "100" 示例 2: 输入: a = "1010", b = "1011" 输出: "10101" 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/add-binary 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ """ bin(10) '0b1010' """ class...
579f9d26b9a105017809237158be99c70c7f8807
BaoziSwifter/MyPythonLeetCode
/pythonLeetcode/350.两个数组的交集-ii.py
1,818
3.75
4
# # @lc app=leetcode.cn id=350 lang=python # # [350] 两个数组的交集 II # # https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/description/ # # algorithms # Easy (44.96%) # Likes: 218 # Dislikes: 0 # Total Accepted: 59.9K # Total Submissions: 131.1K # Testcase Example: '[1,2,2,1]\n[2,2]' # # 给定两个数组,编写一个函数来计算...
b177ffe631dba2755c12fc0729cbfaa80d2bcfeb
BaoziSwifter/MyPythonLeetCode
/pythonLeetcode/107.二叉树的层序遍历ii.py
1,429
4.03125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) 例如: 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回其自底向上的层次遍历为: [ [15,7], [9,20], [3] ] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii 著...
069aa451550d616ab0680646f679d7cc5aff9633
BaoziSwifter/MyPythonLeetCode
/pythonLeetcode/991-坏了的计算器.py
2,054
3.65625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/2/20 15:08 # @Author : Beliefei # @File : 991-坏了的计算器.py # @Software: PyCharm """ 在显示着数字的坏计算器上,我们可以执行以下两种操作: 双倍(Double):将显示屏上的数字乘 2; 递减(Decrement):将显示屏上的数字减 1 。 最初,计算器显示数字 X。 返回显示数字 Y 所需的最小操作数。 示例 1: 输入:X = 2, Y = 3 输出:2 解释:先进行双倍运算,然后再进行递减运算 {2 -...
a4b8ac47d62d25126dcdb5fdc2dd5d5017084d08
BaoziSwifter/MyPythonLeetCode
/pythonLeetcode/94.二叉树的中序遍历.py
2,551
3.96875
4
# # @lc app=leetcode.cn id=94 lang=python # # [94] 二叉树的中序遍历 # # https://leetcode-cn.com/problems/binary-tree-inorder-traversal/description/ # # algorithms # Medium (68.81%) # Likes: 315 # Dislikes: 0 # Total Accepted: 75.2K # Total Submissions: 109.2K # Testcase Example: '[1,null,2,3]' # # 给定一个二叉树,返回它的中序 遍历。 # ...
30ce806c5f6f168715310c587503f19396401b19
BaoziSwifter/MyPythonLeetCode
/pythonLeetcode/108-将有序数组转换为二叉搜索树.py
1,016
3.71875
4
""" 将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 示例: 给定有序数组: [-10,-3,0,5,9], 一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树: 0 / \ -3 9 / / -10 5 """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right ...
9d65969127401d0dc8ea12052e370e00e3a7354d
BaoziSwifter/MyPythonLeetCode
/pythonLeetcode/collect-sort.py
5,384
3.71875
4
# 冒泡排序 def bubbleSort(arr): for i in range(1,len(arr)): for j in range(0,len(arr)-i): if arr[j] > arr[j+1]: arr[j],arr[j+1] = arr[j+1],arr[j] return arr # 选择排序 # 算法步骤 # 首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置。 # 再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。 # 重复第二步,直到所有元素均排序完毕。 def selectionSort(arr): arrLen ...
ac1c189338811d43945c5e96f729085aaffe26d8
Halal-Appnotrix/Problem-Solving
/hackerrank/Problem-Solving/Algorithm/Implementation/Grading_Students.py
783
4.125
4
# # The function is expected to return an INTEGER_ARRAY. # The function accepts INTEGER_ARRAY grades as parameter. # def gradingStudents(grades): grades_array = [] for grade in grades: the_next_multiple_of_5 = (((grade // 5)+1)*5) if grade < 38: grades_array.append(grade) ...
146dc48ef417bfb71c20f05822f00010e1f50af7
Halal-Appnotrix/Problem-Solving
/hackerrank/Problem-Solving/Data-Structure/Arrays/2D_Array-DS.py
418
3.625
4
def hourglassSum(arr): add = 0 sum_list = [] for i in range(4): for j in range(4): add = sum(arr[0+i][0+j:3+j])+arr[1+i][1+j]+sum(arr[2+i][0+j:3+j]) sum_list.append(add) return max(sum_list) if __name__ == "__main__": arr = [] for _ in range(6 ): arr.a...
a15b2d4f9ef03ef2bd5d3af3f9133c87d5258d14
Halal-Appnotrix/Problem-Solving
/hackerrank/Problem-Solving/Data-Structure/Tree/Binary_Search_Tree_Lowest_Common_Ancestor.py
1,708
3.671875
4
#Create Node class Node: def __init__(self, info): self.info = info self.left = None self.right = None self.level = None def __str__(self): return str(self.info) #Binary search Tree class BinarySearchTree: def __init__(self): self.root = None d...
6a3b71d50e8ad244c311c32de84163cfb527d70f
Halal-Appnotrix/Problem-Solving
/hackerrank/Problem-Solving/Algorithm/Warmup/Compare_the_Triplets.py
490
3.90625
4
''' Problem Link:-https://www.hackerrank.com/challenges/compare-the-triplets ''' def compareTriplets(a, b): length = len(a) li = [0]*2 for i in range(length): if a[i] > b[i]: li[0] += 1 elif a[i] < b[i]: li[1] += 1 elif a[i] == a[i]: continue...