blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
70c2390aa2840df0fd6bd54fdf3b225b47156288
ThompsonHe/LeetCode-Python
/Leetcode0088.py
733
4.1875
4
""" 88. 合并两个有序数组 给你两个有序整数数组nums1 和 nums2,请你将 nums2 合并到nums1中,使 nums1 成为一个有序数组。 说明: 初始化nums1 和 nums2 的元素数量分别为m 和 n 。 你可以假设nums1有足够的空间(空间大小大于或等于m + n)来保存 nums2 中的元素。 示例: 输入: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 输出:[1,2,2,3,5,6] """ class Solution: def merge(self, nums1, m, nums2, n): ...
68685b3dca14bf22fa3e8d8812b6bbf19b0fdb70
snulion-study/algorithm-adv
/jenny/sorting/[필수]단어정렬.py
602
4
4
""" [정렬] 백준 1181번 sort의 기준이 정해져 있을 때, python 내장 함수의 sorted와 lambda로 sort 기준의 우선순위를 정해준다. : sorted(iterable, key= lambda x: [기준]) 내장함수 말고 직접 구현하는게 핵심인 것 같은데 난 귀찮으니 생략. """ def solution(word_list): word_list = sorted(set(word_list), key=lambda x: [len(x), x]) for w in word_list: print(w) return ...
64d20b6eaa4d2e27e2de96eb0605545e31388771
maxbergmark/misc-scripts
/codereview/find_repeating.py
1,622
3.625
4
import time import numpy as np def find_repeating(lst, count=2): ret = [] counts = [None] * len(lst) for i in lst: if counts[i] is None: counts[i] = i elif i == counts[i]: ret += [i] if len(ret) == count: return ret def find_repeating_fast(lst): n = len(lst)-2 num_sum = -n*(n+1)//2 + np.sum(lst)...
3e3be3fa5c1327be35a6d33c27793733ddc86e60
CoreyPrachniak/Van-Eck-Sequence
/main.py
810
3.53125
4
print("Please input a tuple, (M, p). The output is the probability that for a random index, n < M, the nth member of the Van Eck sequence is zero or within p percent of n.") tuple = input() M, p = map(int, tuple[1: len(tuple) - 1].split(", ")) #STEP 1: Fill an array called dontknow with the first M entries of the Van...
60547004e6c76cffce141ef6f13e4c4248bccd67
lapa19/wcmentor16
/flow.py
2,291
3.765625
4
# variables a=5 #integers print(a) pi = 3.14 #float my_name='aparna' #strings var = True #boolean my_var = 5 #integer my_var = 'tree' #string #strings: #immutable #string concatenation x='ap' y='arna' x+y #Indexing:strings are indexed x[0] #gives 'a' #negative indexing: x[-1] #gives 'p' #slicing: y[0:2] #gives 'ar'...
6d6ed9b2e5717b040a2339f22cf21166c0dc2919
fwzlyma/OpenCV-in-3h
/7_face_detection.py
1,267
3.5625
4
# 项目 : Python学习 # 姓名 : 武浩东 # 开发时间 : 2021/7/12 12:27 import cv2 import numpy as np def useCam(): faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # how to import a webcam cap = cv2.VideoCapture(0) # 0 mean webcam object cap.set(3, 640) # the width ID is 3 ...
fb3641017158cbb1d4596a9ec532733d6d7b6645
Jagadish2019/The_Valley_Boot_Camp
/3Mar19/dynamicfib.py
215
3.578125
4
def fib_efficient(n,d): if n in d: return d[n] else: ans = fib_efficient(n-1, d) + fib_efficient(n-2, d) d[n] = ans return ans d = {1:1,2:1} a = int(input("enter a number\t")) print(fib_efficient(a,d))
a65c3967e2a92b7a3d8fdbd45b446118e59abe6c
i386net/python_crash
/the begining/others/5-8_hello_admin.py
853
3.828125
4
users = ['sponge bob', 'patrick', 'sandy', 'admin'] new_users = ['john', 'Patrick', 'michael', 'rose', 'sara'] if len(users) == 0: print('We need to find some users!') else: for user in users: if user == 'admin': print('Hello admin, would you like to see a status report?') else: ...
a82f52439bdec84adc211792bb23cae313e93915
preboe/stapik
/stepik_2/stepik_1.1.py
1,944
4.34375
4
# Задача 1. Напишите программу, которая считывает одну строку. Если это строка «Python», # программа выводит «ДА», в противном случае программа выводит «НЕТ». # # Решение. Программа, решающая поставленную задачу, может иметь вид: word = input() if word == 'Python': print('ДА') else: print('НЕТ') # Задача 2. ...
3180b33c49d1c819ffe2dbd3f579046ed6abcd78
jpmolinamatute/labs
/server/Python/pass.py
1,900
3.734375
4
#! /home/juanpa/Projects/labs/server/Python/.venv/bin/python import random import time import string import argparse import pyperclip def generate(length, alphanu): if not isinstance(length, int): raise TypeError("length must be an integer") if length < 8: raise ValueError("length must be grea...
c040f6ef4acf04f243de67e2c10f8b7260ded1b8
AlekssandraMurzyn/pythonKurs
/zestaw2.py
3,873
3.765625
4
# zadanie 2.1 print("##################### zadanie 2.1 ##################### ") longInt = 92835893724000 a = str(longInt) b = a.count("0") print(b) # zadanie 2.2 print("##################### zadanie 2.2 ##################### ") x = 5 print(x == 5 and 3) # 3 is not 0 and x is indeed 5 so its True. print(x == 5 and 0)...
83b70ea5bcb07921616114ff1c59f9ae858745e1
tganesan70/epai3-session6-tganesan70
/test_part1.py
11,286
4
4
#''' #Python code for poker game #''' import random import itertools import part1 ## Globals # Card values vals = [ '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '10' , 'jack' , 'queen' , 'king' , 'ace' ] # card suits suits = [ 'spades' , 'clubs' , 'hearts' , 'diamonds' ] # Question 1: Create the complete deck of...
558315a7d9bb3a2a64c673b7c38d1bd39fb0c934
nikhilcusc/HRP-1
/ProbSol/magicSquare2.py
1,137
3.734375
4
''' You will be given a 3x3 matrix s of integers in the inclusive range 1-9. We can convert any digit a to any other digit b in the range 1-9 at cost of |a-b|. Given s, convert it into a magic square at minimal cost. Print this cost on a new line. ''' def getAllSquares(): allMagicSquares=[ [[2, 7, 6], [9, ...
41d106be54c4e9991ecbf67047ba74aaeecb527a
NakulK48/Project-Euler-Solutions
/52.py
928
3.53125
4
#PROBLEM 52 #Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. import time start = time.clock() i = 1 truths = [] while True: truths = [] a = str(i) f = str(6*i) if len(f) == len(a): A, B, C, D, E, F = [], [], [], [], [], [], for j in...
704c9c2259021c2d53443dcb82480e3aefa65a90
DenisEke/BSC_Artificial_Intelligence
/Computational Thinking/Assignment 3/Corona_Proof.py
838
3.890625
4
#Ask for number of friend in a friendly way print("Hey I am here to check whether your party is corona proof. How many friends are you planning to invite? ") numberFriends=int(input()) #If less than or equal to 6 friends if numberFriends<=6: #ask for friends name print("This should work out fine. Tell me thei...
8febba19c20a2ed2caf560f0dc7bbf16e88e7485
arnava2001/Python-Code
/Anagram Game/anagram.py
2,106
3.5625
4
import threading import time import enchant import random from collections import Counter score = 0 def genLetterPool(): vowels = ['a', 'e', 'i', 'o', 'u'] letters = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p','r', 's', 't', 'v', 'w', 'x', 'y'] s = '' for n in range(2): s+=ran...
97e5e4247df8709ddddd41fbd6495ba900a89b40
taxijjang/algorithm
/연속된 수의 합.py
228
3.703125
4
import math def solution(num, total): center_value = math.sqrt(total) for start in range(1, num + 1): pass return 1 if __name__=="__main__": num = 3 total = 12 print(solution(num, total))
104feeeb1f402f6807ff950524d6faa1789d649e
kimjeonghyon/Algorithms
/Python/MovingAverage.py
523
3.671875
4
def movingAverage(data,num) : ret = [] for i in range(num-1,len(data)): sum = 0 for j in range(0,num) : sum += data[i-j] ret.append(sum/num) return ret def movingAverage2(data,num) : ret = [] sum = 0 for i in range(0,num): sum += data[i] ...
4f6dd237004237ab01ce4a5b5b59fa85f93e805e
ravi7501/computer-graphics
/dda_algo.py
832
3.828125
4
import matplotlib.pyplot as ravi def round(n): return int(n+0.5) def drawDDA(x1, y1, x2, y2): x = [x1] y = [y1] steps = abs((x2 - x1) if abs(x2 - x1) > abs(y2 - y2) else (y2 - y1)) dx = (x2 - x1) / float(steps) dy = (y2 - y1) / float(steps) print(((round(x[0]...
f16bebd9f409ee6f6ae0941303328c3c57bed054
AlakiraRaven/ProjectEuler
/Problem3_LargestPrimeFactor.py
566
4.375
4
''' the code works for smaller numbers, does not scale well ''' import math if __name__ == "__main__": x = 0 x = int(input('Please input a positive integer X: ')) while x < 0: print('Your number is negative, please input a positive value.') x = int(input('Please input a positive integer ...
5f755ffc052eab58dc4c2ca9a41f5f5f2f5be3e8
vikask1640/Demogit
/calculator.py
1,571
4.09375
4
#..............CALCULATOR................ import math def calculator(): print("Enter the values of a") a=float(input()) print("Enter the vaues of b") b=float(input()) print() print("Addition of numbers") def adds(a,b): add=a+b print(add) adds(a,b) print()...
589a92512421b75379dbc3f7547fdd0736ff68ca
leekyunghun/bit_seoul
/ML/m32_outlier.py
1,750
3.515625
4
############################### 데이터 안에 있는 이상치 확인 ################################ import numpy as np # def outliers(data_out): # quartile_1, quartile_3 = np.percentile(data_out, [25, 75]) # print("1사분위 : ", quartile_1) # 3.25 # print("3사분위 : ", quartile_3) # 97.5 # iqr = quartile_3 - quartile...
c12083e8cbc0301457e00b4fdbc979d807035dfe
vincent-vega/adventofcode
/2017/day_03/3.py
1,577
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def _square_coord(square: int) -> (int, int): max_steps, step_cnt = 1, 1 direction = 0 # 0: RIGHT, 1: UP, 2: LEFT, 3: DOWN x, y = 0, 0 for _ in range(2, square + 1): step_cnt -= 1 x += 1 if direction == 0 else -1 if direction == 2 else 0 ...
883100fd6e40f554397b5a4b47fb44823b1801a0
kushagrapatidar/Newton-School-Code-Contests
/September 2021 Code Contest/Que_01.py
246
3.59375
4
nums=input() nums=nums.split() for i in range(len(nums)): nums[i]=int(nums[i]) lst=[0,1,2] lst[2]=max(max(nums[0],nums[1]),nums[2]) lst[0]=min(min(nums[0],nums[1]),nums[2]) for _ in nums: if _ not in lst: lst[1]=_ print(lst[1])
5b57068b8e06fbc23bc498cd1ee0750c46f8563f
MrCsabaToth/IK
/2019Nov/practice4/critical_connections_dfs_recursive.py
829
3.5
4
def findCriticalConnections(noOfServers, noOfConnections, connections): critical = [] visited = [False] * noOfServers def dfs(source): visited[source] = True for neighbor in adj_list[source]: if not visited[neighbor]: dfs(neighbor) for connection in connecti...
8930c19930bd1649d78e55e03c4f5e95add89727
TulasiGupta/master
/python/sqllite/user.py
1,138
3.65625
4
import sqlite3 class User(object): def __init__(self, _id, username, password): self.id = _id self.username = username self.password = password @classmethod def find_by_username(cls, username): print("username "+username) connection = sqlite3.connect("data.db") ...
113f54d89baebe043e68e9ade756d880eb9d9a01
ElvinChen1994/PythonPlan
/Chapter1/test_loop.py
1,044
3.875
4
# -*- coding:utf-8 -*- # @Time: 2021/7/26 12:26 下午 # @Author: Elvin '''for in ''' sum = 0 for x in range(100): sum += x print(sum) '''增加歩长''' sum = 0 for x in range(1,100,2): sum += x print(sum) '''while 循环''' import random answer = random.randint(1,100) counter = 0 while True: counter += 1 number =...
1221e5fb34a0eb201bad210deea12039a50660c1
hieugomeister/ASU
/CST100/sobeledge.py
2,647
3.5
4
import image import math import sys # Code adapted from http://www.cl.cam.ac.uk/projects/raspberrypi/tutorials/image-processing/edge_detection.html # Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. # this algorithm takes some time for larger images - this increases the amount of time ...
5a8b9bbb1f68ee455845b89775352d003b19c369
bokveizen/leetcode
/836_Rectangle Overlap.py
330
3.734375
4
# https://leetcode-cn.com/problems/rectangle-overlap/ class Solution: def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool: x1 = max(rec1[0], rec2[0]) y1 = max(rec1[1], rec2[1]) x2 = min(rec1[2], rec2[2]) y2 = min(rec1[3], rec2[3]) return x2 - x1 > 0 and y2 ...
4b223a623f3e5fc16b658c35d192758c8f1a746c
rose317/network_program
/demo_正则表达式.py
239
3.671875
4
import re names = ["name","_name","2_name","__name__","name#name"] for i in names: ret = re.match(r"[a-zA-Z_][a-zA-Z0-9_]*$",i) if ret: print("变量名%s符合要求" % i) else: print("变量名%s非法" % i)
8a514cffbc1a232db2a9b4b9a5c68df84d9597d2
sinhasaroj/Python_programs
/properties_use_cases/property_method_for_type_checking.py
626
3.71875
4
class Person: def __init__(self,first_name): self._first_name = first_name # Getter Function @property def first_name(self): return self._first_name # Setter Function @first_name.setter def first_name(self,value): if not isinstance(value,str): raise Val...
bc745644f3ffbfc7e64a751c38dc87397ec09f35
pidddgy/competitive-programming
/dmoj/modefinding2.py
97
3.515625
4
#!python3 N = int(input()) nums = input().split() nums2 = [int(x) for x in nums] # print(nums)
e991eb8dad2e62bf377d3c3bd96a5c73920f7691
Timur597/First6team
/6/Tema6(Dict,Set)/14.d_100.py
159
3.5
4
14 Задание farm_2 = {"cow", "horse", "donkey", "cat", "dog"} farm_1 = {"dog", "cat", "mouse", "sheep"} farm_2.difference_update (farm_1) print (farm_2)
4bbd1023acd3458bb63ecac6a6e8738bb9d10c9b
WeAreAVP/avp-tools
/otter-txt-to-vtt-script/otter-txt-to-vtt.py
4,681
3.671875
4
''' Purpose: Converts TXT files to WebVTT files. Usage: 'python [path to otter-txt-to-vtt.py]' or 'python3 [path to otter-txt-to-vtt.py]' depending on your environment config. ''' import os import re from datetime import datetime from datetime import timedelta use = input('Would you like to convert a single TXT or a...
73f196e0f76d888b5f88db7f8795f7df39021317
gitprouser/LeetCode-3
/interleave.py
801
3.921875
4
class ListNode: def __init__(self, x): self.val = x self.next = None def interleave(p, q): dummy = ListNode(0) cur = dummy while p is not None and q is not None: cur.next = p cur = cur.next p = p.next cur.next = q cur = cur.next q = q.next ...
7317cd586606f98c6459206d78b6860c59b05e73
rocketII/project-chiphers-old
/playfair.py
8,436
3.53125
4
def playfair_encrypt(secret, key, junkChar): ''' Encrypt using playfair, enter secret followed by key. Notice we handle only lists foo['h','e','l','p'] English letters only lowercase. :param secret: text string of english letters only, :param key: string of english letters only, thanks. :param ...
087e1a8d7ff4eb6c3b626089053ce6c53b6e3965
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/word-count/8ab446165df2444eb0982eedf5eddad9.py
166
3.765625
4
import re def word_count(input): words = re.split(r"\s+", input) distinct_words = set(words) return {word: words.count(word) for word in distinct_words}
95a8e1125977a42a52a86becdc1d37687c2e28df
Illugi317/forritun
/aefingarprof/student.py
1,060
4.125
4
from collections import defaultdict NUMBER_OF_PEOPLE = 4 NUMBER_OF_GRADES = 3 MAX_DECIMALS = 2 def get_names_and_values(name_dict): counter = 0 while counter != NUMBER_OF_PEOPLE: name = input("Student name: ") for x in range(0,NUMBER_OF_GRADES): grade = input(f"Input grade number {x+...
ae8f0acc4a2a41d0f57285042ca789c393abf409
lyk4411/untitled
/pythonWebCrawler/student.py
1,958
3.890625
4
class Student(): def __init__(self, name): print("Student init") super(Student, self).__init__() if __name__ == "__main__": s1 = Student("XIAOMIN") s1.english =90 class Person(object): __slots__ = ('_name', '_age', '_sex') ##限制基类变量只能有这三个属性,实例对象无法增加新的属性,这就防止了用户误输入 def __init__(se...
722467ce4d1de29c49aae9180694de36832e763f
riteshbisht/dsprograms
/arrays/searching/problem1.py
572
3.765625
4
""" Given an array A[] and a number x, check for pair in A[] with sum as x Write a program that, given an array A[] of n numbers and another number x, determines whether or not there exist two elements in S whose sum is exactly x. """ arr = [1, 2, 3, 4, 5, 6, 7, 8] if __name__ == '__main__': k = 7 myset = set...
940877bf3e62ccc8ab6fadc39d04ab950a6a7b63
Keshpatel/Python-Basics
/OOP Python/Classes and Instance.py
630
4
4
# Python Object-Oriented Programming class Employee: def __init__(self, first,last,pay): self.first = first self.last = last self.pay = pay self.email = first + "." + last + '@company.com' def fullname(self): return '{} {}'.format(self.first, self.last) emp_1 = Employe...
780b3b7b03917782f8392c5caf6ba9059048b9d4
sameerktiwari/PythonTraining
/Basics/Addition.py
115
3.921875
4
num1=input("Enter first number") num2=input("Enter second number") print "Addition of two numbers is ",num1+num2
17c7731acd7af27d3604acaa9ef49729e8630830
jixinfeng/leetcode-soln
/python/405_conver_a_number_to_hexadecimal.py
1,360
4.40625
4
""" Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used. Note: All letters in hexadecimal (a-f) must be in lowercase. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zer...
e54ae04f65762d6827ac9e7ab9d9d6c15ae4317a
Rahonam/algorithm-syllabus
/array/contains_range.py
708
3.890625
4
def contains_range(arr:list, start:int, end:int): """ Check if given array contains all elements of some given range using: iteration, time O(n) space O(1) Args: arr: array of integers start: first element of range end: last element of range Returns: boolean: ...
f50dbbea23a9a84011a3bd85b7e587861ee2207a
mariusv/robofinder
/v2.0/search.py
20,294
3.703125
4
#!/usr/bin/python from numpy import * #################################### SEARCH ################################### class Search: """A superclass of search algorithms on grid. """ def __init__(self, search_grid): self.search_grid = search_grid # 2-dimensional search grid self.node_...
5d8694886e104882e15b28cc89e9876295d50349
ro-mak/PythonAlgs
/lesson8/task1.py
873
3.671875
4
from collections import deque # 1. На улице встретились N друзей. Каждый пожал руку всем остальным друзьям (по одному разу). # Сколько рукопожатий было? # Примечание. Решите задачу при помощи построения графа. n = int(input("Number of friends: ")) graph = [] for i in range(0, n): graph.append([1 if j != i else ...
e156cf688a2b96cda8f6b18c1146592d7269aac7
Jason30102212/python_basics_refresher
/10.ListFunctions.py
964
4.1875
4
# 10.ListFunctions numbers = [4, 8, 15, 16, 23, 42] strings = ["One", "Two", "Three", "Four", ] #strings.extend(numbers) # Append to end of list strings.extend("Five") # Append each character as a value to list strings.append("Five") # Append as string to list strings.insert(2, "Two and a half") # First arg is inded...
f70de42a669e899fcb229d87f22c09bdc0dd734d
Edyta68/Akademia-programowania
/test2.py
1,604
3.703125
4
def dic(): thisdict = ({ "apple": 1, "banana": 2, "cherry": 3 }) thisdict["orange"] = 4 thisdict.pop("apple", None) print(thisdict) dic() def word_counter(sentence): from collections import Counter list1 = sentence.split(" ") counts = Counter(...
a824ea3d688d429867b446e7f6d1e5c50575d624
Junaid388/Advanced-Python
/Object Internals and Custom Attributes/ex_attrstorage.py
704
3.78125
4
from vector import * cv = ColoredVector(red = 23, green = 44, blue = 238, p= 9, q= 14) cv.red # stored in a list at __dict__['color'] #cv.p # stored directly in __dict__ print(dir(cv)) print(cv) # look for color variable # Method storage v = Vector(x= 3, y=7) print(v.__class__) print(v.__class__.__dict__) pri...
be164b11af232139ab8bdef69c5c86e5ca148752
Zazzerpoof/DONOTUSE-Code
/Junk/Yeet.py
1,157
3.84375
4
class person: def __init__(self,first_name,last_name,middle_name,favorite_color,fart,eyes,hair,height,weight,age): self.first_name = first_name self.last_name = last_name self.middle_name = middle_name self.favorite_color = favorite_color self.fart = fart self.eyes = ...
df4c79769257929216023a0cc55ecbfa4ede83d0
iliachigogidze/Python
/Cormen/Chapter2/day5/take2/recursion_insertion_sort.py
487
4.09375
4
def main(numbers:list) -> list: print(f'Sort numbers {numbers}') return insertion(numbers) def insertion(numbers): if len(numbers) == 1: return numbers[0] def insertion_sort(numbers): for i in range(len(numbers)-1): key = numbers[i] j = i - 1 while key < numbers[j...
7553b5ecc6cf1b2061d1da56c1e8cd2037f4b09f
AleksandrVladimirovichNaumov/Python
/Lesson9/Naumov_alexander_dz_lesson9_task2.py
1,228
3.9375
4
# Реализовать класс Road (дорога). # определить атрибуты: length (длина), width (ширина); # значения атрибутов должны передаваться при создании экземпляра класса; # атрибуты сделать защищёнными; # определить метод расчёта массы асфальта, необходимого для покрытия всей дороги; # использовать формулу: длина*ширина*масса ...
8130f96043cc320e7d5c122a813c146f3cf121be
JEBatta/agent_with_habits
/test1-streamplot.py
1,108
3.84375
4
""" ========== Streamplot ========== A stream plot, or streamline plot, is used to display 2D vector fields. This example shows a few features of the :meth:`~.axes.Axes.streamplot` function: * Varying the line width along a streamline. This code is a modification from: https://matplotlib.org/gallery/images_conto...
36caaf6d42d93e1d25139c88d2df5edef5e91a41
aritro999/apy
/10_pallindrome.py
345
4.09375
4
def f1(num): temp = num reverse = 0 while num > 0: last_dig = num % 10 reverse = reverse * 10 + last_dig num = num // 10 if temp == reverse: print("The number is palindrome!") else: print("The number is not a palindrome!") num = int(input("Ent...
8a1cebee66d077306785c071223a3ab73701f1a1
jake3991/Stanford_algo
/count_inversions.py
1,412
4.09375
4
def count_inversions(input): #define a single element list to keep track of inversions count=[0] def merge(left,right): #init some varibles output=[] i,j=0,0 #loop while the indexes i and j are less than the length of left and right while i < len(left) and j < l...
9338572155a771a07431ad67d9b4baabe62007eb
ThompsonBethany01/Python_Practice_Problems
/HackerRank/Introduction.py
2,340
4.21875
4
# Python If-Else ''' Task Given an integer, n, perform the following conditional actions: If is odd, print Weird If is even and in the inclusive range of to , print Not Weird If is even and in the inclusive range of to , print Weird If is even and greater than , print Not Weird ''' #!/bin/python3 import math imp...
d55cfeb3b2a05c46053627797100d1d3450971ac
rnetuka/adventofcode2020
/src/day11.py
3,702
3.859375
4
# --- Day 11: Seating System --- from src.matrix import Matrix import itertools class Seats(Matrix): def __init__(self, width, height): super().__init__(width, height) def adjacent_occupied_seats(self, row, col) -> int: c = [coords for coords in itertools.product((-1, 0, 1), repeat=2)] ...
665e177d6c8f5c41a0f45d180802f57133f1a1ed
vemanand/pythonprograms
/matplotexamples/twoplots.py
290
3.796875
4
import numpy as np import matplotlib.pyplot as plt x = np.arange(0,10,1) y1 = 2*x+5 y2 = 3*x+7 #Use subplot to create two or more plots plt.subplot(1,2,1) #rows,cols,position plt.plot(x,y1) plt.title("First graph") plt.subplot(1,2,2) plt.plot(x,y2) plt.title("Second graph") plt.show()
e29fc7b7cb6f2bcc101e3b2367c4513bfedbbee4
16GordonA/Essay-Writer
/fileparse.py
458
4.125
4
''' Reads through files and parses out paragraphs (denoted by newline characters) ''' def parse(): f = open('input.txt', 'r') text = [] line = f.readline() while(line is not ""): if line is not "\n": text += [line[:len(line)-1]] #-2 is to remove \n from line end ...
227a0118d502be79d6de5c111e1718037a12b7cd
G00364756/Project_Euler
/euler7.py
849
3.890625
4
# Project Euler - Problem 7 # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. # What is the 10 001st prime number? import math def Primenumbers(number): """This function returns the factors of any number""" primes = [] factors = [] ...
c6243b3b8c420a27e10ea6a0282b3ef1947999d6
asdra1v/python_homework
/homework03/Exercise06.py
1,245
4.15625
4
""" 6. Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. Каждое слово состоит из латинских букв в ...
a559d566ffc9e0d737b7272e79784fddef93df46
Gscsd8527/python
/正则表达式/lx_2.py
334
3.828125
4
import re mystr='tanzhenhuatan' test=re.match('tan',mystr) print(test.group()) # 返回匹配的所有字符串,并生成一个列表 print(re.findall('tan',mystr)) # 匹配末尾的字符串的下标 print(test.end()) # 匹配第一个字符串的下标 print(test.start()) # 定位匹配字符串的第一个位置 print(test.pos)
9c008adcb53f5bf97b7bdb08f404f86de41077f8
msano20/Sequence-analysis
/gccontent.py
1,647
3.609375
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 2 13:35:20 2021 Essentially this script reads and parses multiple fasta files before calculating GC percentage and assigning those values and associated fasta IDs into a new dictionary. It will return the ID with the highest GC content. """ file = "string.fasta" def ...
66c9daed3d05553a55e95224cd6cc94a33418bb0
jwyx3/practices
/leetcode/binary-search-tree/construct-binary-search-tree-from-preorder-traversal.py
1,802
3.875
4
# https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/ # Time: O(NlogN) # Space: O(1) # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def...
c5403336fd9befacfa20b2de8fdd28c9703c2a6b
linkem97/holbertonschool-machine_learning
/math/0x04-convolutions_and_pooling/2-convolve_grayscale_padding.py
1,122
3.59375
4
#!/usr/bin/env python3 """ This module has the method convolve_grayscale_padding(images, kernel, padding): """ import numpy as np def convolve_grayscale_padding(images, kernel, padding): """This method performs a convolution on grayscale images with custom padding """ images = np.pad(images, ((0, 0), ...
4c647bc2bf5fdc2f8eb12e7d351a48f34448b257
aallalxndr/cscc11
/linearRegression.py
806
3.609375
4
import math def mean(values): mean = sum(values) / float(len(values)) return mean def covariance(x, meanX, meanY): covariance = 0.0 for i in range(len(x)): covariance +=(x[i] - meanX)* (y[i] - meanY) return covariance def variance(values, mean): variance = sum([(x-mean)**...
c2b13e1895ed846a54c41f5659b2b2cfcc5b8723
xanderyzwich/Playground
/python/puzzles/encoder.py
953
3.71875
4
""" Given a string, Encode any stretch of characters to an encoding of <char><count>. This should account for any character, and should encode upper and lower case differently. """ from unittest import TestCase from tools.decorators import function_details @function_details def encode(plaintext): ciphertext = '' ...
ac0e1ebf2448e20a448f135827cd746d5c0e34d0
LaurentLabine/fcc_demographic_data_analyzer
/demographic_data_analyzer.py
4,802
4.1875
4
import pandas as pd data_url = 'https://raw.githubusercontent.com/LaurentLabine/fcc_data_analysis_python/main/demographic.csv' def calculate_demographic_data(print_data=True): # Read data from file df = pd.read_csv(data_url) df.info() # How many of each race are represented in this dataset? This sho...
4c9e4357ce6bb2beff94e8a110c29ed51dbb82c9
nararodriguess/programacaoempython1
/ex034.py
219
3.6875
4
salario = float(input('Digite o seu salário: ')) if salario > 1250: novo = salario * (1 + 0.1) else: novo = salario * (1 + 0.15) print(f'Seu salário era R${salario:.2f} reais, agora será R${novo:.2f} reais')
8e078af22b22ac81eb324de255de0c10bada7876
TenederoGerard/PANDAS_2
/cars1.py
592
3.6875
4
import pandas as pd #Corresponding .csv file into a data frame named cars using pandas cars = pd.read_csv('cars.csv') #Display the first five rows with odd-numbered columns. B= cars.iloc [:5, 0::2] #Display the row contains the ‘Model’ of Mazda RX4’ C= cars.iloc [:1] #Displays the cylinders (‘cyl’) of th...
c75c080569ec591e78489cdf1f2600a82509dc9e
DoubleS-Lee/python_practice
/practice_02_01.py
3,873
3.765625
4
# 파이썬으로 배우는 알고리즘 트레이딩 # https://wikidocs.net/2843 #%% # 2-1 daum_price = 89000 naver_price = 751000 daum = 100 naver = 20 total = daum_price * daum + naver_price * naver print(total) # 2-2 daum_per = 0.05 naver_per = 0.1 total = daum_price * daum * daum_per + naver_price * naver * naver_per print(total) #%% # 2-...
1b400aa72c54b93a88e12ec9994d08bc7b87688d
hygnic/Gispot
/gispot/test/md/详解pack.py
793
3.546875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # --------------------------------------------------------------------------- # Author: LiaoChenchen # Created on: 2021/1/10 16:36 # Reference: """ Description: Usage: """ # --------------------------------------------------------------------------- import Tkinter as tk # p...
b0cc59677678fa06c24d25e25c390e47907e1e84
VladCincean/homework
/Graph Algorithms/L2/utils.py
782
3.6875
4
class Queue: def __init__(self): self.__q = [] def enqueue(self, x): self.__q.append(x) def dequeue(self): if len(self.__q) == 0: return None x = self.__q[0] self.__q = self.__q[1:] return x def isEmpty(self): ...
0d814843ba4a5f49ff7f452fd9abd4d7d6b26e6c
cnpena/Coding-Practice
/Chapter1/1.6_stringCompression.py
1,874
4.1875
4
#Chapter 1: Arrays and Strings #1.6 String Compression, page 91 #Performs a basic string compression using the counts #of repeated characters. #Example: aabcccccaaa becomes a2b1c5a3 #Iterates through the given string, checking the current #letter against the next letter. If they're equivalent, keep moving. #If not, ...
ce366f1a34aa029740a8d3dc887fea61b6f525a4
aichaitanya/Python-Programs
/factorial.py
247
4.125
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 16 21:45:44 2019 @author: Patil """ n=int(input('Enter Number : ')) def fact(n): if n==1: return 1 else : return n*fact(n-1) print("Factorial is %d" % fact(n))
cf9fabd9ffb6e2704e381aa09271bd5b0bdda6e5
Spaceunit/calculation_methods_2016
/fixed-point_iteration_matrix0.py
2,758
3.71875
4
import math import matrix class FPIM: def __init__(self): self.am = matrix.Matrix([],"Initial matrix") self.commands = { "none": 0, "exit": 1, "test": 2, "clear": 3, "help": 4, "new": 5, "show slist": 6, ...
1f6394627645122b6f8cd0ff8127a3c4b2e37401
rrr5458/python102
/exercises_multiply.py
138
3.78125
4
numbers = [-13, -4, 7, 11, -666, 23, -1134] multiply_list = [] for num in numbers: multiply_list.append(num * 3) print(multiply_list)
632bed19e32e98318b29215d147edd4c1a116867
billkd24/python
/conditions2.py
260
4.15625
4
age = int (input("Please enter your age:")) if age >= 3 and age <= 5: print ("Join Pre-School") elif age >= 6 and age <= 7: print ("Join Grade School") elif age >= 8: print ("Join High School") else: print ("Not elgible to join")
10757d2fdfdca0ebcbd918122694d4ba8d0f3b20
Nchuijangzelie/zenia
/team_chooser/main.py
1,604
4.15625
4
#!/bin/python3 from random import choice #this code below creats a list from player.txt file #players = ['Zelie','Ashley','Rodrigue','Sebastien','Kcenia','Susan','Julius','Amin'] players = [] file = open('players.txt', 'r') players = file.read().splitlines() print(players) #this code creates three empty list teamA = [...
e9774bd92a37c6fddebb8f0fc694ea016e966c86
samcrohub/Exercici2
/Exercici2-YolandaAlonso.py
562
4.0625
4
#! /usr/bin/env python # encoding: utf-8 print "per sortir de la aplicació escriu 'fi' quan et pregunti pel teu nom" salir=0 while salir !="fi": """declaramos aquí la variable para que el while nos vuelva a preguntar""" salir= raw_input ("Escriu el teu nom: ") """ponemos una condición para que nos deje salir""" i...
77309cf8ab11a92f47804ba66e7f58abd705544e
lscosta90br/scripts
/virtualbox-cmd.py
4,667
3.515625
4
"""Programa para interagir com o VirtualBox.""" from os import popen from argparse import ArgumentParser parser = ArgumentParser(prog='virtualbox-cmd cli', description='VirtualBox commandline - programa para manipular hosts virtuais', # NOQA fromfile_prefix_chars='@') ...
2ed2ddb66b5e37169394ff408784c0082b44bb00
ZhengZixiang/interview_algorithm_python
/jianzhi/22.链表中环的入口结点.py
1,113
3.875
4
# 给定一个链表,若其中包含环,则输出环的入口节点。 # # 若其中不包含环,则输出null。 # # 样例 # QQ截图20181202023846.png # # 给定如上所示的链表: # [1, 2, 3, 4, 5, 6] # 2 # 注意,这里的2表示编号是2的节点,节点编号从0开始。所以编号是2的节点就是val等于3的节点。 # # 则输出环的入口节点3. # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.nex...
4294cc2a7c61efd483d79140c96d2fc51f04dc0f
confar/python_challenges
/difference_of_times.py
1,160
4.21875
4
""" Difference of times Given the values of the two moments in time in the same day: hours, minutes and seconds for each of the time moments. It is known that the second moment in time happened not earlier than the first one. Find how many seconds passed between these two moments of time. Input data format The pr...
f737ac2b369b2897222989993371ec11a5e7ec46
KelineBalieiro/Python
/sorveteria.py
855
3.765625
4
class Restaurant(): def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print(self.restaurant_name.title()) print(self.cuisine_type.title()) def open_restaurante(self): ...
9cd123c6fec21d0f1fa0dbde511d254046bcde06
aurel1212/Sp2018-Online
/students/ssankura/lesson06/Activity/calculator/calculator.py
1,672
3.921875
4
""" Lesson06 - Activity 1 Author: Sireesha Sankuratripati Implementation of Calculator """ from .exceptions import InsufficientOperands class Calculator(object): """ Implementation of the Calculator Class """ def __init__(self, adder, subtracter, multiplier, divider): """Constructor for Calculator"...
a5e8035ed68a1c8e95fffab02a5b2ade7fab905a
d-ariel/addhealth
/data_analysis.py
5,004
3.71875
4
import pandas import numpy #read in data set my_addHealth = pandas.read_csv('addhealth_pds.csv', low_memory=False) #upper-case all My Health dataframe column names my_addHealth.columns = map(str.upper, my_addHealth.columns) pandas.set_option('display.float_format', lambda x:'%f'%x) #convert relevant output objects ...
1571e8e0e397d0449fd6c8f689460aa2df8b1c05
jbeaulieu/MIT-ES.S70
/lecture_4/group_4.py
1,522
3.515625
4
################################# # Title: Lecture 4 Group Script # # Lesson: Gauss' Law # # Filename: group_4.py # # Original Author: Joe Griffin # # Most Recent Edit: 1/23/2015 # # Last Editor: Joe Griffin # ################################# # We will calculate the electric field due to a non-unif...
d5120c08f627237137611e7dfee5fb88d458c1ca
marytaylor/LearnPythonTheHardWay
/ex4.py
1,124
4.59375
5
#Here I am declaring how many cars there are cars = 100 # This is how many seats in each car space_in_a_car = 4 #This is how many drivers there are and there can only be 1 driver per a car. drivers = 30 #This is how many people that can ride in a car and this does not count the drivers passengers = 90 #There are not en...
acc29cebf91324c592457aeb90ba36c5b3f3d9fa
joker-Infinite/python
/day_01/function.py
890
3.8125
4
#!/usr/bin/python3 if __name__ == '__main__': def MAX(a, b): if a > b: return a else: return b print(MAX(3, 4)) def address(a): print(id(a)) a = 20 print(id(a)) a = 1 print(id(a)) address(a) print(id(a)) def changeLi...
63e320de4f806fa0741ba46cfa79e91265365813
drewhoener/CS220
/Project 2/src/player.py
1,903
3.546875
4
import random class Player: def make_bet(self, par1_bal): """ :param par1_bal: The balance of the player :return: The bet placed """ pass def want_card(self, par1_hand, par2_bank, par3_list, par4_list): """ :param par1_hand: The player's hand from the ...
91358716ddc829863e3d737ceca6319f46748b43
manishadhakal/python-sms
/iterable_iteratier.py
360
3.734375
4
num=[1,2,3,4,5,6,7] #list ,string,tuple def power(a): return a**2 num2=map(lambda a:a**2,num) #fun,filter,map new_iter=iter(num) print(next(new_iter)) print(next(new_iter)) print(next(new_iter)) print(next(new_iter)) print(next(new_iter)) print(next(new_iter)) print(next(num2)) print(next(num)) for i in num2: ...
7f6e4a4573ba7a5e43ac40c53037c86bc96bad22
pedrochaves/pyjson
/pyjson/utils.py
805
3.515625
4
def is_number(token): return type(token) in [int, float] def is_json_array(token): return type(token) in [list, tuple] def is_string(token): return type(token) in [str, unicode] def is_dict(token): return type(token) == dict def escape(string): to_escape = { '\"': '\\"', "\n"...
ab99bdb883e2f49183c2c20e232869bd08687e92
NhanGiaHuy/CP1404_Pactical
/Prac_03/GPS.py
1,009
3.96875
4
import random def main(): POPULATION = 1000 MAX_INCREASE_BORN = 20 MIN_INCREASE_BORN = 10 MAX_DECREASE_DIED = 25 MIM_DECREASE_DIED = 5 print("Welcome to the Gopher Population Simulator\nStarting population: 1000") for year in range(1, 10): print("year {}\n*****".format(year)) ...
7ac05a1d197d38b6aabad8b930f84f90e1b5872a
pascalmcme/myprogramming
/week3/round.py
147
4.03125
4
number = float(input('Enter a float number:')) print(number) roundedNumber = round(number) print('{} rounded is {}' .format(number,roundedNumber))
6e08d0a904bd06c8864df1f8d51c0a57ee5e797b
sanskruti01/Social-Book
/Social Book App/passwd.py
1,193
3.640625
4
import string def tooShort(pw): 'Password must be at least 6 characters' return len(pw) >= 6 def tooLong(pw): 'Password cannot be more than 12 characters' return len(pw) <= 12 def useLowercase(pw): 'Password must contain a lowercase letter' return len(set(string.ascii_lowercase).intersection(p...
76719fc292d9c3a7a48cee2f09f1e0bb63d750bd
matthewvedder/algorithms
/general/breadth-first-search.py
1,170
3.578125
4
from collections import deque def breadth_first_search(graph, goal, initial_state): node = { 'state': initial_state , 'cost': 0, 'path': [] } frontier = deque() frontier.append(node) explored = [] if goal == node['state']: return node while frontier: node = frontier.popleft() ...
aa6e4478358ea3a95a291bad0d8cb3c2b9f4b712
rxio/Python_Knowledge_Base
/File_Manipulation/0_Files_Intro.py
390
3.96875
4
file = open("numbers.txt", "r") #This line returns the file handle in read mode and stores it in the variable named 'file' #If you don't pass in a second argument, it defaults to "r" print(file) #This prints the file handle print(file.name) #This prints the name of the file print(file.mode) #This prints the mode that ...
b8e98c624417e86dc1ead1dae3f91e156fc0f6e9
nomadlife/project-euler
/p051.py
844
3.921875
4
# check prime. speed up by square root. def isprime(n): if n == 0 or n==1: return False i=2 loop=n**0.5 while i <= loop: if n%i == 0: return False i+=1 return True # replace and check if prime def rep(num, s): text = str(num) if s not in text: ret...
5a5791001e6383e42281bc534f5162bd077dab66
GHshangmu/Python_case
/python_code/algorithm/reverse_num.py
448
3.8125
4
# 反转数字 def reverse(x): """ :type x: int :rtype: int """ str_num = str(x) if x >= 0: res = int(str_num[::-1]) if res <= -2 ** 32 or res >= 2 ** 31 - 1: res = 0 return res else: res = -int(str_num[::-1][0:len(str_num) - 1]) if res <= -2 ** 3...
ef26430871cf803b7b7b809620749bea6a773e5d
erickvaernet/Python3
/5-Ventanas/3ra_ventana.pyw
621
3.828125
4
import tkinter root = tkinter.Tk() frame_1 = tkinter.Frame(root, width="1280", height="700") frame_1.pack() label1 = tkinter.Label(frame_1, text="Primer texto: Hola", fg="black", font=("Arial", 12),) label1.place(x=10, y=20) """Se podria resumir asi si es que no usamos mas la etiqueta: tkin...