blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b934bdcd25d1f38e90d97241c00a92c82a85160e
srisaipog/ICS4U-Classwork
/Learning/Algorithms/Search/Binary VS Linear/main.py
1,211
3.9375
4
""" Complete the provided spreadsheet by changing the values in this program according to the spreadsheet and record the results. """ import timeit from typing import List def linear_search(target: int, data: List) -> int: for i, num in enumerate(data): if num == target: return i ret...
6d72ca5f0317d5bef54078bc91fbc9003d05ef8a
Takkoyanagi/playground
/leetcode/reverse_linkedlist.py
471
3.796875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: self.prev = None self.curr = head while (self.curr != None): self.nextTemp = ...
f69676f8c3d40905eeaac153e174f564cbc0e6a7
JaiJun/Codewar
/7 kyu/Highest and Lowest.py
1,043
4.21875
4
""" In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number. Example: high_and_low("1 2 3 4 5") # return "5 1" high_and_low("1 2 -3 4 5") # return "5 -3" high_and_low("1 9 3 4 -5") # return "9 -5" Notes: All numbe...
1e24f12e4f1cc916d28f4e7f2dcbc89ab63cf2ac
irenenikk/advent-of-code-18
/5/5.2.py
883
3.671875
4
import re inputs = open("input.txt", "r").read() # add each character to stack # with a new character, check if reacts with the top element of stack def react(a, b): if a.isupper() and a.lower() == b: return True if b.isupper() and b.lower() == a: return True return False def react_...
958ab7b44ece1d8b84bf8daf79aec5b3e90c6af1
mcdy143/datamining
/clustering/clustering2.py
5,342
3.53125
4
# k-means clustering # Daniel Alabi and Cody Wang import math import random from heapq import * import matplotlib.pyplot as plt import numpy as np from scipy.interpolate import spline # selects centers using the "refined cluster centers" # algorithm which clusters a random sample of the data # n times (n=50 in this ...
0ae2d97e4a316b5f51b1b17935dc4b569376fec6
NidhiSingh0068/Open-CV--Computer-Vision
/chapter5.py
511
3.59375
4
##Size of Image import cv2 import numpy as np img = cv2.imread("Resources/lam.jpg") print(img.shape) #shape of image (183, 275, 3) imgResize = cv2.resize(img, (150, 100)) print(imgResize.shape) #resizing an image -increase or decrease imgCropped = img[0:100,200:275] #Cropping an image - (height[start...
55f67ed4143042d359c567d14b8592fb94131b92
AFatWolf/cs_exercise
/9.3. Exercises/Q6.py
122
3.609375
4
def checkList(l): if len(l): return "List is not empty" return "List is empty" l = [1] print(checkList(l))
08c76392ebcb8bf75c441d0823d3d6afa09ae8bc
kineugene/lessons-algorithms
/lesson-2/task_6.py
1,089
3.5625
4
import random import sys from time import sleep if __name__ == '__main__': print("У вас есть 10 попыток, чтобы угадать число от 0 до 100. " "После каждой попытки будет подсказка, больше или меньше указанного загаданное число.") number = random.randint(0, 100) for i in range(10): guess = i...
941fca493d53154e40bc155aa23ba7d47c29917c
Libardo1/TemperaturePrediction
/Weather.py
9,957
3.84375
4
''' Created on Feb 11, 2012 @author: Andrew Taber ''' ## Workflow: ## 1. Take filename argument and open a file, read from file ## 2. Process the data in the file (i.e. organize data by grouping by location in a list indexed by date, then aggregating into dictionary of locations) ## 3. On each location's dataset, perf...
817bc4ff4d5f7a70c25ab577fad34d42e9e69399
0x1701/Python_intro
/analyze_mdout.py
1,107
3.828125
4
import os import argparse #to open the file for reading # tell argparse to handle arguments parser = argparse.ArgumentParser(description="parsers amber mdout files to extract total energy.") #Tell argparse what argument to expect parser.add_argument("path", help="The filepath to the file.") #Get arguments from the us...
9dca946da68c7d677e563459d1d47e61ff7fe645
manhtung2111/Dictionary_Excercises
/Try_Except_Exercises.py
207
3.5
4
try: print(x) print("Hello World") print("Em tên là Ngô Mạnh Tùng") except: print("sai mẹ r :))))") else: print("Cứ tiếp tục in :))") finally: print("Em chào các anh các chị")
149605d4a282d55ea7d823da465a2cacc5d096f3
jadenpadua/ICPC
/core/trees/deserialize-serialize-bst.py
1,221
3.75
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None import queue class Codec: def serialize(self, root): return self.serializeHelper(root) def deserialize(self, data): ...
f69df9cf0ead6e28ca9d56cb181d95f893416f80
grudus/AdventOfCode2020
/src/main/python/day03.py
1,002
3.53125
4
from operator import mul from functools import reduce def first_star(forest): return traverse_forest(forest, (3, 1)) def second_star(forest): slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)] trees = [traverse_forest(forest, slope) for slope in slopes] return reduce(mul, trees) def traverse_forest...
915c93e79e7791e5b715ae2b37cc91f974a3d7be
WangYihang/CrackMe
/templates/keygen.py
724
3.5625
4
#!/usr/bin/env python # encoding:utf-8 import sys def check_password(username, password): v2 = 0 v7 = 0 for k in password: v7 = v2 v3 = 0 if (k > ord("0")) and (k < ord("9")): v3 = 1 v5 = v7 if v3 == 1: break v5 = ord(...
d8ce8dbb879999bd81a0e9eda8398c434b3b5501
qmnguyenw/python_py4e
/geeksforgeeks/algorithm/easy_algo/5_15.py
22,463
3.65625
4
Dividing a Large file into Separate Modules in C/C++, Java and Python If you ever wanted to write a large program or software, the most common rookie mistake is to jump in directly and try to write all the necessary code into a single program and later try to debug or extend later. This kind of approach is ...
76b44ad297ee12925564f02654dc13c5f1bd26b7
cerebrumaize/leetcode
/jump_game/1.py
579
3.546875
4
#!/usr/bin/env python '''code description''' # pylint: disable = I0011, E0401, C0103 class Solution(object): '''Solution description''' def canJump(self, nums): '''Solution func description''' max_step = 0 for ind in xrange(0, len(nums)): if ind > max_step: r...
d19c847e8ec592ec6021267489f6fed9f02ad622
EojinK1m/Practice_Algorithm_Problems
/programmers/level2/짝지어_제거하기.py
316
3.59375
4
#https://programmers.co.kr/learn/courses/30/lessons/12973 def solution(s): s = list(s) stack = [s.pop()] while s: a = s.pop() if not stack or not stack[-1] == a: stack.append(a) else: stack.pop() if stack: return 0 else: return 1
664e07e1052a211b7e8c9f320d18216e81b1a452
AndreaGarofoli/Rosalind-problems
/2.RNA.py
457
4.25
4
""" Problem An RNA string is a string formed from the alphabet containing 'A', 'C', 'G', and 'U'. Given a DNA string tt corresponding to a coding strand, its transcribed RNA string uu is formed by replacing all occurrences of 'T' in tt with 'U' in uu. Given: A DNA string tt having length at most 1000 nt. Return: T...
4791cfc1780df006274f8855eeafcfb8d4dfbb29
yuliang123456/p1804ll
/第二月/于亮_p10/aa/build/lib/工厂模式.py
943
3.515625
4
class CarStore(object): def createCar(self,typeName): pass def order(self,typeName): self.car = self.createCar(typeName) self.car.move() self.car.stop() class XiandaiCarStore(CarStore): def createCar(self,typeName): self.carFactory=CarFactory() return self.car...
c0c4ba9ebb6e47a3101d3936aafa7e985a5d77f8
danahagist/100_Days_Of_ML_Code
/day25_weightedMean.py
1,247
4.125
4
# Task: Given an array, X, of N integers and an array, W, representing the respective weights of X's elements, # calculate and print the weighted mean of X's elements. # Your answer should be rounded to a scale of 1 decimal place (i.e.,12.3 format). # ----------------------------- Solution -------------------------...
88a783206b3c4e7c453f2d3642be299b9031ef2f
danahagist/100_Days_Of_ML_Code
/day10_queuesAndStacks.py
2,873
3.984375
4
# Task: # To solve this challenge, we must first take each character in s, enqueue it in a queue, # and also push that same character onto a stack. # Once that's done, we must dequeue the first character from the queue and pop the top character off the stack, # then compare the two characters to see if they are the ...
3f5ecf5fa3a0e4af7a12813d94c434d370fa8725
louism33/dailyProblems
/day5.py
686
4.25
4
''' Good morning! Here's your coding interview problem for today. This problem was asked by Jane Street. cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. Given this implementation of cons:...
cfb98b1a5e76de2353ab8e87f20abc550d61547e
ganavi12/python-program
/interview programs/first_second_list.py
312
3.765625
4
l1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] l2 = [0, 1, 1, 0, 1, 2, 2, 0, 1] l3 = [] for i in range(len(l1)): for j in range(len(l2)): print(i,l2[j]) if i == l2[j]: l3.append(l1[i]) print(l3) # zipped_list = zip(l1 + l2) # y = [x for _, x in sorted(zipped_list)] # print(z)
09f945f3047167c6c560911dd321f177cc94d5c8
morningred88/data-structure-algorithms-in-python
/Stack-Queue/queue_with_stack_recursive.py
635
3.578125
4
class QueueStackRecursive: def __init__(self) -> None: self.stack = [] def enqueue(self, data): self.stack.append(data) def dequeue(self): if len(self.stack) == 1: return self.stack.pop() item = self.stack.pop() dequeued_item = self.dequeue() se...
aa1cb2407e7c4911ef847eb4899bcb16af277a3d
saikatsengupta89/PracPy
/HCK_HappinessDegree.py
469
3.546875
4
# There is an array of length n # There is a from itertools import groupby def calculate_happiness(n,m,arr, a,b): pos=0 neg=0 for i in arr: if i in a: pos=pos +1 if i in b: neg=neg +1 print(pos-neg) if __name__=="__main__": n, m= input().split("...
b439e8a25dd631752dff480eef604411b0434ad3
gabrieldepaiva/Exercicios-CursoEmVideo
/Python_Exercicios/ex006.py
202
3.984375
4
n = int(input('Digite um número: ')) print() print('O dobro de {} vale {}.'.format(n,n*2)) print('O triplo de {} vale {}.'.format(n,n*3)) print('A raiz quadrada de {} vale {}.'.format(n,int(n**(1/2))))
bc405d451730f0062e9628586c25f8e625b364e9
jessie0624/BasicAlgo
/BasicAlg/HeapSort.py
1,236
4.03125
4
def HeapSort(data): ##将数组构造成大根堆 def heapInsert(data, index): while (data[index] > data[(index - 1)//2 if index - 1 > 0 else 0]): data[index], data[(index - 1)//2] = data[(index-1)//2], data[index] index = (index - 1)//2 if index - 1 > 0 else 0 ##某个位置变化后做调整 ...
45bd7886fc480f6df1f79bc35309869b13f83e23
lakshmi2710/LeetcodeAlgorithmsInPython
/Q2Search.py
1,551
3.65625
4
class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if len(nums) == 0: return -1 index = self.getIndex(nums, 0, len(nums) - 1) print index if index == -1: ...
e48d0691c1e3ac9eb15b0352e7f92eb194a83ca9
HooFaya/test
/剑指第二轮重刷/两个链表的第一个公共结点.py
585
3.609375
4
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def FindFirstCommonNode(self, pHead1, pHead2): if not pHead2 or not pHead1: return cur=pHead1 stack1=[] while(cur): stack1...
3c4d47c1ae93a4190adf2e4479ed18f71c5e7ff4
GitPistachio/Competitive-programming
/HackerRank/collections.Counter()/collections.Counter().py
682
3.65625
4
# Project name : HackerRank: collections.Counter() # Link : https://www.hackerrank.com/challenges/collections-counter/problem # Try it on : # Author : Wojciech Raszka # E-mail : contact@gitpistachio.com # Date created : 2020-10-03 # Description : # Status : Accepted (182396975) # Tags ...
ffd6d7460ceec0c04cd8f0f631d4a31b876ebf12
akalya23/gkj
/15.py
127
3.5625
4
r,b=input().split() r=int(r)+1 b=int(b) for num in range(r,b): if num % 2 == 0: print(num, end = " ")
53ca1c1e96ea41ce0b57ad786743f34a1cc3eb33
paulzfm/LustreAST
/ast2lustre/src/lex_rep.py
867
3.609375
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- file = 'c.txt' f = open(file).read() for each in f.splitlines(): lis = each.split('|') def rep(string): string = string.replace('$', 'SSS') string = string.replace('+', 'ADD') string = string.replace('-', 'MINUS') string = string.replace('*', 'MUL') string = string...
b8dd7dcbd57af41138ef95680edd60166a3b5390
gauresh29/gitfirstpro
/pract5.py
830
4.09375
4
#author gauresh # date 26-10-2021//practical 5 #perpose=practical code with harry 5th pract #function for printing next pallendron def nextpallendrom(num): #print(mylist) if num >10: while not ispallendrom(num) : num += 1 return num else: return num #This function defin...
4a58c4e4e5db0923233f25fb7e263eed9a3fafac
CornellDataScience/Insights-Databowl
/modeling/nn_regression.py
3,568
3.578125
4
# %% [markdown] # # Applying deep learning models to Databowl # Here I use tensorflow to build a feedforward neural net to predict yards # gained on each rushing play. # %% import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import tensorflow_docs as tfdocs np.set_printoptio...
a8f3d747b21760cb458476e61340abb2134e41ef
tt-n-walters/saturday-python
/timer_decorator.py
628
3.5
4
from time import perf_counter def timer_decorator(func): # Define out decorator def wrapper(*args): # Define the higher-order wrapper function start_time = perf_counter() # It accepts *args, meaning any amount of arguments ...
6e6ab0304f094729a16b57fe1d5e4f2a70bec19a
Preethikoneti/pychallenges
/readlines.py
462
3.859375
4
def main(): #read file file = open ( "/Users/kbeattie/Desktop/yesno.txt", "r" ) lines = file.readlines() file.close() #look for patterns countYES = 0 countNO = 0 for line in lines: line = line.strip().upper() # print ( line ) if line.find("YES")!= -1 and len(line)==3: countYES = countYES + 1 if lin...
e364f9174e6135d7c898871fee67522d8e117bbc
MeerKat98/Morse-Code
/Morse.py
469
3.5625
4
#MeerKat #Variables arrAlpha = [] arrMorse = [] word = '' #Main alphaFile = open("Alphabet.txt") morseFile = open("Morse.txt") for line in alphaFile: arrAlpha.append(line) for line in morseFile: arrMorse.append(line) alphaFile.close() morseFile.close() word = raw_input("Enter word to convert to morse code: ")...
d40ab8362f5d957ac8596a48e658cff0f5020687
ThibautBlomme/Informatica5
/05 - EenvoudigeFuncties/Pythagoras.py
396
3.734375
4
#variabelen a = float(input('Geef de lengte van de eerste rechthoekszijde: ')) b = float(input('Geef de lengte van de tweede rechthoekszijde: ')) from math import sqrt c = sqrt(pow(a, 2) + pow(b, 2)) #formule print(str('In een rechthoekige driekhoek met rechthoekzijden a = ' + str('{:.2f}'.format(a)) + ' en b = ' + st...
fb0ce579bb1a84d4f311e451c21bfbecdc72f38d
Harinarayan14/p97
/p97.py
882
4.1875
4
# import random for finding a random number import random; # Random Number number = random.randint(1,100); # Text print("Number Guessing Game"); print("Guess from 1 to 100"); print("You have 10 chances."); #Chances chances =0; # While Loop while chances < 10: # Input guess = int(input("Enter your guess ")...
c0a6b34e674c5317726375178463e51bc0e8efb2
linkeshkanna/ProblemSolving
/HackerRank.30.Days/splitStringOddEven.py
565
3.8125
4
# HackerRank # https://www.hackerrank.com/challenges/30-review-loop/problem if __name__ == '__main__': n = int(input()) inputs = [] for i in range(n): inputs.append(input()) print(inputs) oddList, evenList = "", "" for i in range(n): print(i) print(inputs[i]) cou...
f2246f02e7c6e964986c60844facbe994307d702
ho-kyle/python_portfolio
/040.py
332
3.796875
4
a = [] for i in range(3): e = eval(input('Please enter the first lenght of the triangle: ')) a.append(e) b = max(a) c = min(a) d = sum(a) - b - c if b == c: print('It is an equilateral triangle.') elif c**2 + d**2 == b**2: print('It is an isosceles triangle.') else: print('The triangle i...
761a2d0ba24cd4ca9f417d3144d4d976c349039a
NickolayTernovoy/python-algorithms
/02/tests.py
1,893
3.6875
4
import unittest from LinkedList.Node import Node from LinkedList.List import List class NodeCase(unittest.TestCase): def test_node_can_have_previous_element(self): n1 = Node(1) n2 = Node(2) n2.prev = n1 self.assertIs(n2.prev, n1) def test_node_can_have_next_element(self): n1 = Node(1) n2 = Node(2) ...
6ed3bb7ff0b08af087087df5b67b992ef62becf1
HunterJohnson/Interviews
/epip/rectangle_intersection.py
741
4.0625
4
# write a program that tests if 2 rectangles have a non-empty intersection # if intersection is nonempty, return the rect. formed by their intersection Rectangle = collections.namedtuple('Rectangle', ('x', 'y', 'width', 'height')) # x, y = left lower point def intersect_rectangle(R1, R2): def is_intersect(R1, R2): ...
1c9800e153d11397a355d0e3be4d87cdc7cd725e
viniciusmartins1/python-exercises
/ex075.py
558
4.09375
4
num = ( int(input('Digite um número: ')), int(input('Digite outro número: ')), int(input('Digite mais um número: ')), int(input('Digite o último número: '))) print(f'Você digitou os valores {num}') print(f'O número 9 apareceu {num.count(9)} vezes') if 3 in num: print(f'O valor 3 apareceu pe...
c08d1fa6320866bbec71eb546e88983a98d316bb
umutcaltinsoy/Data-Structures
/Dictionary/dictionary.py
5,655
4.65625
5
# Dictionaries : ''' Dictionary in python is an ordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Key in a dictionary do...
709b3814ad355bc74a160ca03e03ac0ecfcd50c5
arnoqlk/icourse163-Python
/1/MoneyTrans.py
191
3.5625
4
Money = input() if Money[0:3] in ['RMB']: U = eval(Money[3:])/6.78 print("USD{:.2f}".format(U)) elif Money[0:3] in ['USD']: R = eval(Money[3:])*6.78 print("RMB{:.2f}".format(R))
9edd5899c5f2d83b3c8d236fd215cd5341165df7
andrej-sch/learning-from-images
/lfi-01/13-features.py
1,117
3.8125
4
# 1. read each frame from the camera (if necessary resize the image) # and extract the SIFT features using OpenCV methods # Note: use the gray image - so you need to convert the image # 2. draw the keypoints using cv2.drawKeypoints # There are several flags for visualization - e.g. DRAW_MATCHES_FLAGS_DRAW_RICH...
8a4f2a09fb14391a76a9d25bd03ac341da4931df
maryamkh/MyPractices
/Merge_Intervals_Solution2.py
1,659
3.84375
4
#Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, #and return an array of the non-overlapping intervals that cover all the intervals in the input. #Input: intervals = [[1,3],[2,6],[8,10],[15,18]] #Output: [[1,6],[8,10],[15,18]] #Explanation: Since intervals [1,3] and [2,...
515480233345c7050c261f367ca2a2c90e7d8a6d
Ta-SeenJunaid/Data-Structures-and-Algorithm
/Graph/dfs1.py
682
4.03125
4
class Node(object): def __init__(self, name): self.name = name self.adjancencyList = [] self.visited = False class DepthFirstSearch(object): def dfs(self, node): print(node.name) node.visited = True for n in node.adjancencyList: if not n.visited: ...
06257a7ca16187f01947ef227fbbc035084f30cc
jakeh524/terminal_hangman
/terminal_hangman.py
4,443
3.875
4
#!/usr/bin python3 # Author: Jake Herron # Email: jakeh524@gmail.com import random, os def display(wrong_count): os.system('clear') print("------------------------------") if(wrong_count == 0): print(" _________ ") print(" | | ") print(" | ") print(" | ...
157200f1482306f44b9bc93a74a6280614dfd8ed
ToucanToco/toucan-data-sdk
/toucan_data_sdk/utils/postprocess/sort.py
1,783
3.875
4
from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: import pandas as pd def sort( df: "pd.DataFrame", columns: Union[str, List[str]], order: Union[str, List[str]] = "asc" ) -> "pd.DataFrame": """ Sort the data by the value in specified columns --- ### Parameters *mandatory...
45a2f1d7d127c00a1be59cdc9cb2fd08aab6c8b7
MrHamdulay/csc3-capstone
/examples/data/Assignment_2/dlmlor002/question3.py
255
4.1875
4
import math num=2 den=0 pi=2 count=1 while(den<2): den=math.sqrt(2 + den) term=num/den pi*=term count+=1 print("Approximation of pi:",round(pi,3)) radius=eval(input("Enter the radius:\n")) area=pi*(radius**2) print("Area:",round(area,3))
214fb8dcc69343e5278aeabb4adf7893f44c786d
wisesky/LeetCode-Practice
/utils/solution.py
691
3.625
4
import sys import importlib import argparse def main(argv): #print(argv) # s1 cmd argv parser #moduleName = argv[1] 必须事先指定参数类型,无法对所有Solution统一 #parser = argparse.ArgumentParser(description='Solution Time ') #parser.add_argument('p1', type=int) # s2 input moduleName = input('Type in the modu...
f22a5f5e3532d8e334c7efbae8ecc56b71268cca
brycereynolds/practice
/algorithms/sorting/ComparatorSorting.py
934
3.8125
4
# See: https://www.hackerrank.com/challenges/ctci-comparator-sorting from functools import cmp_to_key class Player: def __init__(self, name, score): self.name = name self.score = score def __repr__(self): return repr(self.name, self.score) def comparator(a, b): ...
7c6f71ef75bfb22655359f4f42bbbd9d53b574cb
dsinnovated/Workshops
/10-11-19 Intro_ML/load_data.py
1,823
3.90625
4
#import packages import pandas as pd # The as keyword lets you shorten the name of the import package original = pd.read_csv("simple_retail.csv") # Load the .csv file - It is important to note that you have to include the extension as well. # If...
72b7fdd295099cfa9aaf3ecd6b0a4e1574229231
Merovizian/Aula22
/Desafio109/teste.py
1,052
3.75
4
from leiaint import leiaint from Desafio109 import moeda print(f"\033[;1m{'Desafio 107 - Algumas funcoes matematicas':*^70}\033[m") numero = 0 # loop para um menu facil while True: escolha = leiaint(''' 1 - Criar/alterar numero 2 - Seu Dobro 3 - Sua Metade 4 - Aumentar 5 - Diminuir 0 - Sai...
45f91ab175bb97124ced9bd90e2b35806cd80049
004sharmag/Python-practice
/board.py
4,367
4.21875
4
# a list for the game board board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"] # states the game is on going. Will break later on game_on_going = True winner = None # first move current_player = "X" # function that prints out the board def display_board(): print(board[0] + " | " + board[1] +...
d0e166362951aa61daf12fafba5d7ab2b6900e9d
meghamohan/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/2-uniq_add.py
128
3.5
4
#!/usr/bin/python3 def uniq_add(my_list=[]): uniqList = set(my_list) sumTheList = sum(uniqList) return (sumTheList)
a78a44092bae2e9e1746d9a638dad069611f1f82
glimmercn/Euler-Project
/src/solution/p65.py
272
3.609375
4
''' Created on 2011-7-14 @author: huangkan ''' from fractions import Fraction from Mytools import contif2frac e=[2] for i in range(1,34): e.append(1) e.append(i*2) e.append(1) print(len(e)) a=contif2frac(e) print(sum([int(i)for i in list(str(a.numerator))]))
728ec706cb0543595e1168fcc7cd483231f61b1e
yamaton/codeforces
/problemSet/510A-Fox_And_Snake.py
573
3.578125
4
#!/usr/bin/env python3 """ Codeforces 510 A. Fox and Snake @author yamaton @date 2015-07-30 """ def solve(n, m): grid = [['.'] * m for _ in range(n)] for i in range(0, n, 2): grid[i] = '#' * m for i in range(1, n, 2): if i % 4 == 1: grid[i][-1] = '#' elif i % 4 == 3: ...
1573936f6403a401828c92a08b23c90774fb3359
elenaborisova/Python-Basics
/13. Exam Prep Questions/04. SoftUni Past Exams/02. Repainting.py
636
3.765625
4
paper_amount_needed_sq_m = int(input()) paint_amount_needed_liters = int(input()) water_amount_needed_liters = int(input()) labor_hours_needed = int(input()) paint_amount_needed_liters += paint_amount_needed_liters * 0.1 paint_price = paint_amount_needed_liters * 14.50 paper_amount_needed_sq_m += 2 paper_price = pape...
565fc6b25994e25e201f76f1bc9f1bc27b9499ae
bufordsharkley/advent_of_code
/2015/day12.py
738
3.703125
4
import json def get_total_num(data, ignore_red=False): if isinstance(data, basestring): return 0 elif isinstance(data, int): return data elif isinstance(data, list): return sum(get_total_num(item, ignore_red=ignore_red) for item in data) elif isinstance(data, dict): if ...
0c109d910af292b8d6351c5dad3f3203bebd2b1f
akash1601/algorithms_leetcode_solution
/solutions/3sumCloset.py
427
3.65625
4
def threeSumCloset(nums,target): #3sumCloset nums.sort() result = nums[0] + nums[1] + nums[2] for i in range(len(nums)-2): j, k = i+1, len(nums) -1 sum = nums[i] + nums[j] + nums[k] while j < k: if sum == target: return sum if abs(sum - target) < abs(result - target): result = sum if sum < t...
0f465862031ff320422374243b97134f2eab58fa
liliarc96/Aula-Python
/Exercicios_2/adolescentes.py
393
4.03125
4
''' • Faça um programa que lê a idade de várias pessoas (enquanto o úsuario digitar valores positivos). Em seguida, o algoritmo deverá apresentar a quantidade de adolescentes (de 12 a 17 anos). ''' adolescentes = 0 idade = 1 while idade > 0: idade = int(input("Digite a idade: ")) if idade >=12 and idade <=17: adol...
242b0e3c99716154607c7d33fcffc61e387f3922
mayankchutani/warmup
/dynamic_programming/fibonacci.py
423
3.796875
4
__author__ = 'mayank' def fib(n): """ Finds the fibonacci value of n :return: integer value """ if n == 0: return 0 if n == 1 or n == 2: return 2 fibList = [None for i in range(n)] fibList[0] = 0 fibList[1] = fibList[2] = 1 for i in range(2, n): fibList...
41159614db05f9c25ea06121e0bd37912d0be17c
parkjmjohn/Computer_Graphics
/Project4/parser.py
2,639
4.1875
4
from display import * from matrix import * from draw import * """ Goes through the file named filename and performs all of the actions listed in that file. The file follows the following format: Every command is a single character that takes up a line Any command that requires nextuments must have those next...
9b1078a82e55647db9a2a140f062f574832d5070
harverywxu/algorithm_python
/01_string/03动荡子序列/978. 最长动荡子数组.py
2,280
3.703125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 978. Longest Turbulent Subarray A subarray A[i], A[i+1], ..., A[j] of A is said to be turbulent if and only if: For i <= k < j, A[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even; OR, for i <= k < j, A[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is...
87c2e287ea700db0fba71022785ae6fd41f0e15f
vicioussyndicate/JSmulligan
/matchingdbfid.py
615
3.828125
4
##This function is to match the returned dbfIDs of each card, and then return the name ## of the string so that the cards a readable. Also we want to be able to write this function ## so we can organize the decklists that people are matching import json def matchdbfid(dbfid): """ Takes in the dbfid, and the di...
37e49590a3ba92b1cc782f95ae92f7531be72edf
IvaAndreeva/Anagrams
/anagrams-processor/task.py
2,552
3.609375
4
#!/usr/bin/env python import sys backup_words = ["ail", "tennis", "nails", "desk", "aliens", "table", "engine", "sail", "tail","sailq","aliensd", "taile", "pail", "pile", "lipea", "in", "sin", "sina"] alpha = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",...
85acc6b0c2ef4e5bf4ec74b5f867d1ad7cd433ad
KaneLindsay/KNN-Digit-Recognition
/KNN/myKNN.py
5,801
3.921875
4
from sklearn import datasets from sklearn.model_selection import train_test_split import numpy as np def main(k_neighbors, dataset, test_data_percent): """ Predict a class for every test image and find the accuracy of the algorithm using k neighbours. Parameters ---------- k_neighbors : int ...
64caa5b22addf183a7845fa308f5686d808a4024
nguyenngochuy91/companyQuestions
/google/lexiSmallestEquiString.py
2,096
3.671875
4
# -*- coding: utf-8 -*- """ Created on Fri Dec 6 17:57:10 2019 @author: huyn """ #1061. Lexicographically Smallest Equivalent String #Given strings A and B of the same length, we say A[i] and B[i] are equivalent characters. #For example, if A = "abc" and B = "cde", then we have 'a' == 'c', 'b' == 'd', 'c' == 'e'. #...
d764d30574e70de77ef9ae854e1d6cdfb4ba603f
ynbstyj/MachineLearning
/KNN/02/knn_iris.py
463
3.609375
4
import pandas from sklearn.neighbors import KNeighborsClassifier from sklearn.cross_validation import train_test_split dataset = (pandas.DataFrame(pandas.read_csv("iris.csv"))).values X = dataset[:, 0:3] y = dataset[:, 4] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) cl...
db5cc553c851c669ac68fe9f0675415625054c42
Srinithyee/AI-Lab
/EX 5/166_ai_work.py
2,495
3.546875
4
import math import random class point: def __init__(self, x: int, y: int): self.x = x self.y = y def dist(self, p2) -> int: dx = self.x - p2.x dy = self.y - p2.y return math.sqrt(math.pow(dx,2) + math.pow(dy, 2)) @staticmethod def genran...
7d60d1b4e1af63911fd83d883d06f83e64b02fca
Love-yadav/LibraryManagment
/video_101_Mini_project_library_harry_version.py
2,311
4.25
4
#create a library class #display book # lend book - who owns the book if book is not present # add book #return book # harry library=Library(listofbooks ,libraryname) # dirctionary=(books-nameoftheowner) # create main function and run an infinte while loop asking # user for their input class Library: ...
606e1b4bb6d9b52a752a624c62f16f919bb219be
Wecros/aoc-2020
/day5/part1.py
1,195
3.890625
4
#!/usr/bin/env python import fileinput def compute_row(line): """Compute the row of the seat.""" low: int = 0 high: int = 127 for char in line[:7]: diff: int = high - low if char == 'F': # lower half high -= int(diff / 2 + 0.5) elif char == 'B': ...
1034ed2df456a96fa2e782c0d56200c3a1762a0f
greymatterrobotics/simple-movement-example
/robot.py
472
3.515625
4
from sr import * import time R = Robot() #Move forward R.motors[0].target = 100 R.motors[1].target = 100 print "Moving forward" time.sleep(2) #Turn around R.motors[0].target = 50 R.motors[1].target = -50 print "Turning" time.sleep(2) #Just change this line until the amount it turns is about 180 degrees #Come back R...
3de83a2d105982888743371cf7bb889c3daf9e55
fucilazo/Dragunov
/机器学习/数据科学/sample5.1_图论.py
1,578
3.53125
4
import networkx as nx import matplotlib.pyplot as plt G = nx.Graph() # 定义一个图对象 plt.subplot(221) G.add_edge(1, 2) # 在两个节点之间添加边(图本身不带节点,它会自动创建) nx.draw_networkx(G) # 图的位置(节点)自动生成 # nx.draw_networkx(G, node_color='g', node_shape='*', edge_color='b') plt.subplot(222) # 增加节点 G.add_nodes_from([3, 4]) # ...
97374fc9176a37d4c97b83bf68feed57363a9fe2
jacosta18/Raindrops_project
/formal_code.py
600
4.5
4
# Stage 1: Identifying the sounds and factors # - The following part of the code demonstrates the factors 3, 5, 7 being assigned sounds: sound_factors = { 3: "Pling", 5: "Plang", 7: "Plong", } # Return the sound effects assigned to factors. def raindrops(number): return [sounds for a, s...
61b82ab899c2d77e842f75ba49b592d279230f77
KennyTzeng/LeetCode
/905/main.py
502
3.65625
4
class Solution: def sortArrayByParity(self, A): """ :type A: List[int] :rtype: List[int] """ i, j = 0, len(A)-1 while i < j: # to find the next odd number while not A[i] % 2 and i < len(A)-1: i += 1 # to fin...
4026d3956f96d1e304c5dd20c10fd37bcc47d53b
devankit01/jumblewordapp
/Tkinter/Jumbleinpy/main.py
1,472
3.59375
4
# App from tkinter import * from tkinter import messagebox import random ans=['python','lucknow','italy','engineer','maths','automata','india','laptop','phone'] jmb=['yponth','ckluonw','altit','gieneren','tsham','mautota','idani','ptlapo','openh'] sc=['1','2','3','4','5','6','7','8','9'] logic = rando...
723b16c126dce4dee2143dac5bf66dfe117050c4
SriYUTHA/PSIT
/Examination/Donut.py
490
3.84375
4
"""Donut""" def main(): """Donut""" cost = int(input()) num_buy = int(input()) num_free = int(input()) num_want = int(input()) pack = num_want//(num_buy+num_free) remain = num_want%(num_buy+num_free) get_donut = 0 cost_all = 0 if remain >= num_buy: pack += 1 else: ...
8af55c40874e837e7de3956330d793261c8ca578
Cammr94/Spring2019_Python1_Data119
/Week6/reading_homework_5a_reverse_string.py
983
4.5625
5
# -*- coding: utf-8 -*- """ Cameron Reading Data 119 Python 1 3/7/2019 Homework 5 A Outputing String and Reverse from user """ #Getting String from User, and store it and find its length user_string = input("Please type a sentence out and I'll reverse it!: ") string_length = len(user_string) #Setting word "Accumaltor...
24a972ac0f8c428e245100f69cb0992e234c1b11
kevin-goulding/AdventOfCode
/2019day6.py
1,517
3.578125
4
filename = "...\\2019day6.txt" infile = open(filename, 'r') orbits = [] for line in infile: orbits.append(line) infile.close() #orbitDict is a dictionary where key:value = (orbiter): (planet that orbiter orbits) orbitDict = {} for orbit in orbits: twoOrbitList = orbit.split(")") orbitDict[twoOrb...
58a9e1f70ea4273cddc29adc6893dd16a1c84371
ChoiKangM/buildUpPython
/Week_4/function.py
141
3.515625
4
def func1(): a = 10 print("func1에서 a의 값: %d" % a) def func2(): print("func2에서 a의 값: %d" % a) a = 20 func1() func2()
86a775aaec8325e8fffe23b26c66c8db9ae5d6e7
caique-santana/CursoEmVideo-Curso_Python3
/PythonExercicios/ex024 - Verificando as Primeiras Letras de um Texto.py
363
4.15625
4
#Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com o nome "SANTO". # Meu cidade = input('Qual o nome da sua cidade: ') print('O nome da cidade começa com "Santo" ? \033[1;36m{}\033[m.'.format('SANTO' in cidade.upper().split()[0])) # Gustavo Guanabara cid = str(input('Em que cidade você nas...
5ac5c991451eba2c198a63d69170e980cca112d0
git874997967/codingbat_solutions
/lone_sum.py
190
3.625
4
def lone_sum(a, b, c): sum = a + b + c if a == b and a == c : return 0 if a == b: return c elif a == c: return b elif c == b: return a return sum
713e0acbbd51ec5cf88525441b19291be7507e09
Kallil12/anotacoes-cursos-online
/Datacamp - Python - Statistical Thinking/1 - statistical thinking pt 1/lecture-1.py
2,653
3.859375
4
# exercise 1 # Import plotting modules import matplotlib.pyplot as plt import seaborn as sns # Set default Seaborn style sns.set() # Plot histogram of versicolor petal lengths plt.hist(versicolor_petal_length) # Show histogram plt.show() # ----//---- ----//---- ----//---- ----//---- ----//---- ----//---- # exerci...
bef2e9d79c8639b289fcd0ea06fc5279159d15b2
kkoutoup/Kickstart-Github-Project
/Dependencies/select_language.py
768
4
4
# What language will you be scripting in? def select_language(): print("\n=> Select language") languages = ["Python", "Ruby", "Javascript", "HTML"] for index, language in enumerate(languages, start = 1): print(f'{index}: {language}') user_input = int(input("What language will you be scripting in? Select ind...
12c204fc1a5bd4877ef53f36683d2dc83c3c5de8
TesztLokhajtasosmokus/velox-syllabus
/week-04/4-recursion/hints/fractal.py
332
3.84375
4
from tkinter import * root = Tk() canvas = Canvas(root, width=600, height=600) canvas.pack() def fractal(x, y, size): canvas.create_oval(x, y, x+size, y+size, fill="yellow") if size < 10: pass else: fractal(x, y, size/2) fractal(x+size/2, y+size/2, size/2) fractal(5, 5, 590) root...
cefe8c8678beca7b5fb691ef8b2c552ccef70d3b
zzinsane/algos
/Equili.py
423
3.578125
4
# you can write to stdout for debugging purposes, e.g. # print "this is a debug message" def solution(A): # write your code in Python 2.7 total = sum(A) current = 0 result = [] for idx,ele in enumerate(A): if total - ele - current == current: result.append(idx) current += ele return result[0] if len(re...
2c9074eab6f28c40f707f512fffe7f4ef903bc6e
CezOni/MTEC2280
/Oniszczuk_Calculator2.py
500
4.0625
4
import sys calc = 0 number = input("Enter first number: ") sign = input("Enter symbol you need (+,-,*,/): ") number2 = input("Enter second number: ") if(sign == '+'): calc = int(number) + int(number2) print(number + '+' + number2) if(sign == '-'): calc = int(number) - int(number2) print(number + '-' + number2) ...
79eb13b1119ee706cd9fd004b99b2b392ad0a9f7
TMenezesO/Python-UERJ
/Aula5/ex1.py
289
3.609375
4
list_values=[10,20,30] def listoperations(lista): print (max(lista)) print (min(lista)) print (sum(lista)) def listmultiply(lista): res = 1 for x in lista: res = res*x print (res) return res listoperations(list_values) listmultiply(list_values)
7f85b1c86e44a38b5248019ed1c42c5d6848e355
alabavery/Email_Distribution_Tool
/file_management.py
2,279
3.578125
4
import os import glob import json import file_io def prompt_user_to_save_csv(data_dir_path): # no return csv_file_list = [] while True: csv_file_list = glob.glob(data_dir_path + '/*.csv') if len(csv_file_list) > 0: break print() print("..........................................................") print...
65945db4d3716494bba09d5f8b63cf501c5ea028
hrssurt/lintcode
/lintcode/1281 Top K Frequent Elements.py
983
3.765625
4
"""*************************** TITLE ****************************""" """1281 Top K Frequent Elements.py""" """*************************** DESCRIPTION ****************************""" """ Given a non-empty array of integers, return the k most frequent elements. """ """*************************** EXAMPLES ***...
e68df0f29fd26bdbbb084600edfe39ce4ce2f201
Jason003/interview
/Reverse Linked List.py
565
3.828125
4
class Solution: def reverseList(self, head: ListNode) -> ListNode: dummy = ListNode() dummy.next = head curr = head while curr and curr.next: nxt = curr.next curr.next = nxt.next nxt.next = dummy.next dummy.next = nxt return dum...
8fc9517babab7411219386ba6d28821ee6f711ed
josephJJ1020/rockpaperscissors_CLS
/rockpaperscissors.py
4,365
3.96875
4
import random import time class Player: def __init__(self): self.score = 0 self.pick = None class Game: def __init__(self): self.choices = ["rock", "paper", "scissors"] self.options = ["Y", "N"] self.running = True def run(self): if self....
e4b918492414a6fa4f03097b311aba74d43c7a2f
ysmirnova/PythonCourse
/utils/Fibo.py
321
4.3125
4
def generatefibonacci(length): if length == 0: return 0 else: a, b = 0, 1 for i in range(2, length + 1): a, b = b, a + b return b if __name__ == "__main__": print("Input number for number in Fibonacci sequence: ") n = int(input()) print(generatefibonacci(n))...
90d0c67a147c853476bddb62210947414df7ccf8
Rishu-aery/python_learning
/pallavi_practice.py
1,015
4
4
# Input : test_str = ‘Gfg is best’ # Output : {‘Gfg’: 1, ‘is’: 1, ‘best’: 1} # # Input : test_str = ‘Gfg Gfg Gfg’ # Output : {‘Gfg’: 3} # str = " pallavi is the good girl" # a = {i:str.count(i) for i in str.split()} # print(a) # Python – Convert Snake case to Pascal case # Input : geeks_for_geeks # Output : GeeksforG...
9508afbd284b963958a63c15830e3629f24aac23
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_135/3135.py
692
3.5
4
#!/usr/bin/env python from sys import stdin cases = int(stdin.readline()) for i in range(1, cases + 1): row = int(stdin.readline()) for k in range(1, 5): line = stdin.readline() if k == row: nums = set(line.split()) row = int(stdin.readline()) for k in range(1, 5): ...
6d67a44123c2175c79b4a7105fb923554b71b01e
MuYi0420/newstudy
/python/function-2.py
482
3.921875
4
def discounts(price, rate): final_price=price*rate # print (old_price) 结果为全局变量,可以访问,不可修改 old_price = 50 print ('修改后的old_price的值是1:',old_price) #新建一个old_price的局部变量,与全局变量无关 return final_price old_price = float(input('请输入原价: ')) rate = float(input("请输入折扣率: ")) new_price=discounts(old_price, rate) p...